您的位置:首页 > 其它

LeetCode 18. 4Sum

2017-05-10 21:33 429 查看
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: 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]
]


Subscribe to see which companies asked this question.
4sum问题,其实和3sum一样,在最外层多加一个for循环。import java.util.HashSet;
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if(nums.length<4){
return ans;
}
int len = nums.length;
Arrays.sort(nums);
Set<List<Integer>>set = new HashSet<List<Integer>>();
for(int i=0;i<len-3;i++){
for(int j=i+1;j<len-2;j++){
int k = j + 1;
int l = len - 1;
while(k<l){
int value = nums[i]+nums[j]+nums[k]+nums[l];
if(value == target){

set.add(new ArrayList<Integer>(Arrays.asList(nums[i],nums[j],nums[k],nums[l])));
while(k<l&&nums[k]==nums[k+1])k++;
while(k<l&&nums[l]==nums[l-1])l--;
k++;
l--;
continue;
}
if(value<target){
k++;
}
else{
l--;
}
}
}
}
List<List<Integer>> res = new ArrayList<List<Integer>>(set);
return res;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: