您的位置:首页 > 职场人生

LeetCode 018 4Sum

2014-02-13 22:55 302 查看
题目

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)


数组,找出4个数的和等于制定目标,输出所有的答案。

思路

A 和3SUM的思路一样,但是细节不一样,而且不一样的很有意思。

B 这次的答案一定要用set先放,为什么?因为在3个数的时候,我们有限制,让搜寻过程中不会出现重复;但是4sum的时候,出现重复,我们无能为力。

C 为什么无能为力?最外层这次是两个数的组合,想想检查到-1,-1,-1,2这样的数列的时候,需要跳过的是[-1,-1]的这种组合,可是没有指针用来记录这样的组合。

D java 最后可以直接把set 变成ArrayList 还是很方便的。

代码

public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
Set<ArrayList<Integer>> ans
= new HashSet<ArrayList<Integer>>();
if(num==null|| num.length<4){
return new ArrayList<ArrayList<Integer>>(ans);
}
Arrays.sort(num);
int n = num.length;
for(int i =0;i<n-3;i++){
for(int j=i+1;j<n-2;j++){
int l = j+1;
int r = n-1;
while(l<r){

if(num[i]+num[j]+num[l]+num[r]==target){
ArrayList<Integer> list = new ArrayList<Integer>();
list.addAll(Arrays.asList(num[i], num[j], num[l], num[r]));
ans.add(list);
l++;
r--;

}
else if(num[i]+num[j]+num[l]+num[r]<target){
l++;
}
else{
r--;
}
}
}
}
return new ArrayList<ArrayList<Integer>>(ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 面试笔试