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]
]
题目分析
和 015 的3sum很像,但是这里是四个元素,015 是第一个元素进行依次遍历,后面两个元素设定指针一前一后遍历。
这里则是前面两个元素做一次二重循环。后面两个元素设定指针一前一后遍历。
//代码是大神写的,非原创
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length < 4) return res;
Arrays.sort(nums);
if (nums[0] + nums[1] + nums[2] + nums[3] > target ||
nums[nums.length-1] + nums[nums.length-2] + nums[nums.length-3] + nums[nums.length-4] < target)
return res;
int len_3 = nums.length - 3;
int len_2 = nums.length - 2;
int len_1 = nums.length - 1;
int last_i = nums[0] - 1;
for (int i = 0; i < len_3; i++) {//第一个数,只能遍历到倒数第四个数
if (nums[i] == last_i) continue;
last_i = nums[i];
int last_j = last_i - 1;
for (int j = i + 1; j < len_2; j++) {//第二个数,只能遍历到倒数第三个数
if (nums[j] == last_j) continue;
last_j = nums[j];
int innerTarget = target - last_i - last_j;
if (nums[j+1] + nums[j+2] > innerTarget || nums[nums.length-1] + nums[nums.length-2] < innerTarget) continue;
//后面就和 015 处理方式是一样的了
int left = j + 1, right = len_1;
while (left < right) {
int innerSum = nums[left] + nums[right];
if (innerSum == innerTarget) {
res.add(Arrays.asList(last_i, last_j, nums[left], nums[right]));
left++;
right--;
while (nums[left] == nums[left-1] && left < right) left++;
while (nums[right] == nums[right+1] && left < right) right--;
} else if (innerSum < innerTarget) {
left++;
} else {
right--;
}
}
}
}
return res;
}
}