1. Two Sum
public int[] twoSumHashMap(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(target-nums[i])) {
return new int[] {map.get(target-nums[i]), i};
}
map.put(nums[i], i);
}
return null;
}
public int[] twoSumTwoPointer(int[] nums, int target) {
N[] ns = new N[nums.length];
for(int i = 0; i < nums.length; i++) ns[i] = new N(nums[i], i);
Arrays.sort(ns, new Comparator<N>() {
public int compare(N n1, N n2) {
return Integer.compare(n1.v, n2.v);
}
});
int l = 0, r = nums.length - 1;
while(l < r) {
if(ns[l].v + ns[r].v == target) return new int[] { ns[l].i, ns[r].i };
else if(ns[l].v + ns[r].v < target) l++;
else r--;
}
return null;
}
class N {
int v;
int i;
public N(int v, int i) {
this.v = v;
this.i = i;
}
}