public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();
if(num.length < 4) return result;
Arrays.sort(num);
for(int i = 0; i < num.length - 3; i++) {
for(int j = i + 1; j < num.length - 2; j++) {
int start = j + 1;
int end = num.length - 1;
while(start < end) {
int sum = num[i] + num[j] + num[start] + num[end];
if(sum == target) {
ArrayList<Integer> tmp = new ArrayList<Integer>(4);
tmp.addAll(Arrays.asList(num[i], num[j], num[start++], num[end--]));
set.add(tmp);
}else if(sum > target) {
end--;
}else{
start++;
}
}
}
}
result.addAll(set);
return result;
}
4Sum
最新推荐文章于 2021-08-20 00:33:10 发布