您的位置:首页 > 其它

[Leetcode] 18. 4Sum

2015-03-12 22:30 295 查看
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d =
target? Find all unique quadruplets in the array which gives the sum of target.

Note:

Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.

For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

A solution set is:
(-1,  0, 0, 1)
(-2, -1, 1, 2)
(-2,  0, 0, 2)

import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num.length < 4) return result;
Arrays.sort(num);
for(int i = 0; i < num.length - 3; i++){
if(i == 0 || num[i] != num[i - 1]){
for(int j = i + 1; j < num.length - 2; j++){
if(j == i + 1 || num[j] != num[j - 1]){
int start = j + 1;
int end = num.length - 1;
while(start < end){
if(num[i] + num[j] + num[start] + num[end] == target){
ArrayList<Integer> set = new ArrayList<Integer>();
set.add(num[i]);
set.add(num[j]);
set.add(num[start]);
set.add(num[end]);
result.add(set);
start++;
end--;
while(start < end && num[start] == num[start - 1]){
start++;
}
while(start < end && num[end] == num[end + 1]){
end--;
}
} else if(num[i] + num[j] + num[start] + num[end] < target){
start++;
} else {
end-- ;
}
}
}
}
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: