四数之和
问题描述:
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:答案中不可以包含重复的四元组。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [], target = 0
输出:[]
思路:
和三数之和类似,先套用两层循环,然后双重指针左右来查询。
注意的点是第二层i 如果等于第一层的q是不用跳过循环的
代码:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> a= new LinkedList<List<Integer>>();
Arrays.sort(nums,0,nums.length);
int len=nums.length;
if(len<4) return a;
for(int q=0;q<len;q++){
for(int i=q+1;i<len;i++){
if (q > 0 && nums[q] == nums[q - 1]) continue;
if (i > 0 && nums[i] == nums[i - 1]&&i-1!=q) continue;
int t = target-nums[q]-nums[i];
int j = i + 1, k = len - 1;
while (j < k) {
if (nums[j] + nums[k] > t) {
k--;
} else if (nums[j] + nums[k] < t) {
j++;
} else {
// find
List<Integer> ans = new LinkedList<>();
ans.add(nums[q]);
ans.add(nums[i]);
ans.add(nums[j]);
ans.add(nums[k]);
a.add(ans);
// 去除临近相同的元素
while (j < k && nums[j] == nums[j + 1]) j++;
while (j < k && nums[k] == nums[k - 1]) k--;
j++;
k--;
}
}
}
}
return a;
}
}