Skip to content

Instantly share code, notes, and snippets.

@ianomad
Created October 22, 2016 22:57
Show Gist options
  • Save ianomad/166a600c4a7aa98d4d0a25db16804d39 to your computer and use it in GitHub Desktop.
Save ianomad/166a600c4a7aa98d4d0a25db16804d39 to your computer and use it in GitHub Desktop.
public class Solution {
class Entry {
int pos;
int val;
Entry(int pos, int val) {
this.pos = pos;
this.val = val;
}
}
public int[] twoSum(int[] nums, int target) {
ArrayList<Entry> data = new ArrayList<Entry>();
int pos = 0;
for(int num : nums) {
data.add(new Entry(pos, num));
pos++;
}
Collections.sort(data, new Comparator<Entry>() {
public int compare(Entry o1, Entry o2) {
return o1.val - o2.val;
}
});
int i = 0, j = data.size() - 1;
while(i < j && data.get(i).val + data.get(j).val != target) {
if(data.get(i).val + data.get(j).val < target) {
i++;
} else {
j--;
}
}
return new int[] {data.get(i).pos, data.get(j).pos};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment