给你一个由 n
个整数组成的数组 nums
,和一个目标值 target
。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]]
(若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a
、b
、c
和d
互不相同nums[a] + nums[b] + nums[c] + nums[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 = [2,2,2,2,2], target = 8 输出:[[2,2,2,2]]
四数之和也就是在前篇三数之和的基础上增加一个for循环
三数之和确定一个数字,使用左右指针来循环,四数之和就是再确定一个数字,使用两个指针指向nums[i]后面的两端循环判断,就比前篇三数之和多了一个循环
例如[1,0,-1,0,-2,2],排序完为【-2,-1,0,0,1,2】锁定【-2,-1, ......】,两个指针分别为除了锁定值的两端,指针分别为0,和2,【-2,-1,0,2】相加为-1不等于0,因为列表是从小到大,右移是和会增加,左移和会减小,-1比目标0小,所以需要把值加大才可能等于0,所以只能左指针右移
左指针右移后发现还是0,【-2,-1,0,2】,结果一致,跳过这次循环,继续寻找
【-2,-1,1,2】,发现等于0了,就把结果推入,以此循环
var fourSum = function(nums, target) {
const final = [];
if (nums.length < 4) {
return final;
}
nums = nums.sort((a,b)=>a-b)
for(let i =0;i<nums.length-3;i++){
if (i > 0 && nums[i] === nums[i - 1]) continue;
for(let j =i+1;j<nums.length-2;j++){
if (j > i + 1 && nums[j] === nums[j - 1]) continue
let left = j+1 , right = nums.length-1
while(left<right){
let count = nums[i] + nums[j] + nums[left] + nums[right]
if(count === target){
final.push([nums[i], nums[j],nums[left] , nums[right]])
while (left<right&& nums[left] == nums[left+1]) left++; // 去重
while (left<right&& nums[right]== nums[right-1]) right--;
left++
right--
}
if(count>target){
right--
}
if(count<target){
left++
}
}
}
}
return final
};