您的位置:首页 > 其它

18. 4Sum

2016-07-16 19:38 239 查看
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]
]


和3sum的思想类似,外层循环多了一层。
public static List<List<Integer>> fourSum(int[] nums, int target)
{
List<List<Integer>> retarr=new ArrayList<>();
int len=nums.length;
if(len<4)
return retarr;

HashSet<Integer> hashset=new HashSet<>();
Arrays.sort(nums);
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
int lo=j+1;
int hi=len-1;
while(lo<hi)
{
int sum=nums[i]+nums[j]+nums[lo]+nums[hi];
if(sum<target)
lo++;
else if(sum>target)
hi--;
else {
ArrayList<Integer> arrayList=new ArrayList<>();
int hash=nums[i]*7+nums[j]*97+nums[lo]*10007+nums[hi]*100000007;
if(!hashset.contains(hash))
{
arrayList.add(nums[i]);
arrayList.add(nums[j]);
arrayList.add(nums[lo]);
arrayList.add(nums[hi]);
retarr.add(arrayList);
hashset.add(hash);
}
lo++;
hi--;
}
}
}
}
return retarr;
}

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