Thought:
Just like 3Sum, we can write an O(n^3) solution.
Code:
public class Solution {
public ArrayList<ArrayList> fourSum(int[] num, int target) {
Arrays.sort(num);
HashSet<ArrayList> result = new HashSet<ArrayList>();
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
for (int k = j + 1, l = num.length - 1; k < l;) {
int sum = num[i] + num[j] + num[k] + num[l];
if (sum > target) {
l--;
}
else if (sum < target) {
k++;
}else{
ArrayList tmp = new ArrayList();
tmp.add(num[i]);
tmp.add(num[j]);
tmp.add(num[k]);
tmp.add(num[l]);
result.add(tmp);
k++;
l--;
}
}
}
}
return new ArrayList<ArrayList>(result);
}
}
Code second Round:
public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
Set<ArrayList<Integer>> result = new HashSet<ArrayList<Integer>>();
Arrays.sort(num);
for (int i = 0; i < num.length - 1; i++) {
for (int j = i + 1; j < num.length; j++) {
int m = j + 1, n = num.length - 1;
while (m < n) {
if (num[i] + num[j] + num[m] + num[n] < target) m++;
else if (num[i] + num[j] + num[m] + num[n] > target) n--;
else {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);
temp.add(num[j]);
temp.add(num[m]);
temp.add(num[n]);
result.add(temp);
m++;
n--;
}
}
}
}
return new ArrayList<ArrayList<Integer>>(result);
}
}
No comments:
Post a Comment