const fourSum = (nums, target) => {
const res = [];
if(nums.length < 4) {
return res;
}
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]) { // 注意点: j > i + 1,之前写的是j > 1,导致测试用例 nums = [-2,-1,-1,1,1,2,2], target = 0没过
continue;
}
let sum = target - nums[i] - nums[j];
let left = j + 1;
let right = nums.length - 1;
while(left < right) {
if(nums[left] + nums[right] === sum) {
res.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--;
} else if(nums[left] + nums[right] < sum) {
left++;
} else {
right--;
}
}
}
}
return res;
}
来源