Thought:
Sort and iterate the array, for every element, we find the other two elements whose sum is -num[i], it is a O(n^2) solution.
Code:
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
HashSet<ArrayList<Integer>> result = new HashSet<ArrayList<Integer>>();
Arrays.sort(num);
for(int i = 0;i < num.length; i++){
int j = i + 1;
int k = num.length - 1;
while(j < k){
if(num[j] + num[k] + num[i] < 0){
j++;
}else if(num[j] + num[k] + num[i] > 0){
k--;
}else{
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[j]);
tmp.add(num[k]);
result.add(tmp);
j++;
k--;
}
}
}
return new ArrayList<ArrayList<Integer>>(result);
}
}
Code when I met this problem the second time:
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
Set<ArrayList<Integer>> result = new HashSet<ArrayList<Integer>>();
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
twoSum(Arrays.copyOfRange(num, i + 1, num.length), -num[i], result);
}
return new ArrayList<ArrayList<Integer>>(result);
}
public void twoSum(int[] array, int sum, Set<ArrayList<Integer>> result) {
if (array.length < 2) return;
int i = 0, j = array.length - 1;
while (i < j) {
if (array[i] + array[j] < sum) i++;
else if (array[i] + array[j] > sum) j--;
else {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(-sum);
temp.add(array[i]);
temp.add(array[j]);
result.add(temp);
i++; // I forgot this two lines at first...............
j--;
}
}
}
}
No comments:
Post a Comment