Created
October 22, 2016 22:57
-
-
Save ianomad/166a600c4a7aa98d4d0a25db16804d39 to your computer and use it in GitHub Desktop.
Solution for https://leetcode.com/problems/two-sum/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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