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]
]
Solution
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int l = 0; l < nums.length - 3; l++){
if (l > 0 && nums[l] == nums[l-1]){ //避免重复答案
continue;
}
for (int i = l + 1; i < nums.length - 2; i++){
if (i > l + 1 && nums[i] == nums[i-1]){ //避免重复答案
continue;
}
int j = i + 1;
int k = nums.length - 1;
while (j < k){
int sum = nums[l] + nums[i] + nums[j] + nums[k];
if (sum == target){
result.add(Arrays.asList(nums[l], nums[i], nums[j], nums[k]));
j++;
k--;
while (j < k && nums[j] == nums[j-1]) j++; //避免重复答案
while (j < k && nums[k] == nums[k+1]) k--; //避免重复答案
}else if (sum > target){ //如果求和偏大,则右指针左移一位
k--;
}else if (sum < target){ //如果求和偏小,则左指针右移一位
j++;
}
}
}
}
return result;
}
}
网友评论