Question:
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] ]Solution:
Like 3sum, but may be is too slow.........need promotion!
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans= new ArrayList<List<Integer>>();
int len=nums.length;
int k,j;
Arrays.sort(nums);
for(int i=0;i<=len-4;i++)
{
for(int l=i+1;l<=len-3;l++)
{
j=l+1;
k=len-1;
while(j<k)
{
int sum=nums[i]+nums[j]+nums[k]+nums[l];
if(sum==target)
{
List<Integer> tmp=new ArrayList<Integer>();
tmp.add(nums[i]);
tmp.add(nums[l]);
tmp.add(nums[j]);
tmp.add(nums[k]);
ans.add(tmp);
j++;
k--;
while(j<k&&nums[j]==nums[j-1]) j++;
while(j<k&&nums[k]==nums[k+1]) k--;
}
else if(sum<target)
{
j++;
while(j<k&&nums[j]==nums[j-1]) j++;
}
else if(sum>target)
{
k--;
while(j<k&&nums[k]==nums[k+1]) k--;
}
}
while(l<=len-3&&nums[l]==nums[l+1]) l++;
}
while(i<=len-4&&nums[i]==nums[i+1]) i++;
}
return ans;
}
}