您的位置:首页 > 其它

LeetCode18 - 4Sum

2017-07-18 14:17 411 查看
【题目】

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

【思路】

第15题3Sum的升级版,就直接在外面套了一层。。。具体思路见http://blog.csdn.net/shelagao/article/details/75099113

【Java代码】

public class Solution_18_4Sum {
public List<List<Integer>> fourSum(int[] nums, int target){
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums.length < 4)
return result;
Arrays.sort(nums);
for(int i = 0 ; i < nums.length-3 ; i++){
if(i!= 0 && nums[i] == nums[i-1])
continue;
List<List<Integer>> temp = threeSum(Arrays.copyOfRange(nums, i+1, nums.length),target-nums[i]);
if(!(temp.isEmpty()))
for(int j = 0 ; j < temp.size() ; j++)
result.add(Arrays.asList(nums[i],temp.get(j).get(0),temp.get(j).get(1),temp.get(j).get(2)));
}
return result;
}

private List<List<Integer>> threeSum(int[] nums, int target){
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(int i = 0 ; i < nums.length-2 ; i++){
if(i > 0 && nums[i] == nums[i-1])
continue;
else{
int start = i+1, end = nums.length-1;
while(start < end){
if(start != i+1 && nums[start] == nums[start-1])
start++;
else if(end != nums.length-1 && nums[end] == nums[end+1])
end--;
else if(nums[i] + nums[start]+nums[end] < target)
start++;
else if(nums[i] + nums[start]+nums[end] > target)
end--;
else{
result.add(Arrays.asList(nums[i],nums[start],nums[end]));
start++;
end--;
}
}
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode