4Sum
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.
Example:
Given array nums = [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]
]
题目大意
给定一个整数数组,找出a + b + c + d = target的唯一解。
解题思路
此题和3sum 解题思路一样,只是多了一层循环,先确定两个数字,其余两个数字从两边向中间遍历。注意去除重复的数据。
class Solution {
List<List<Integer>> result = new ArrayList<List<Integer>>();
public List<List<Integer>> fourSum(int[] nums, int target) {
if(nums==null&&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;
for(int j=i+1;j<nums.length-2;j++){
if(j>i+1&&nums[j]==nums[j-1])
continue;
int left=j+1;
int right=nums.length-1;
while(left<right){
if(nums[i]+nums[j]+nums[left]+nums[right]==target){
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[left]);
list.add(nums[right]);
result.add(list);
left++;
right--;
while(left<right&&nums[left]==nums[left-1]) left++; //避免重复
while(left<right&&nums[right]==nums[right+1])right--;
}
else if(nums[i]+nums[j]+nums[left]+nums[right]<target)
left++;
else
right--;
}
}
}
return result;
}
}