1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| function fourSum(nums: number[], target: number): number[][] { const len = nums.length if (len < 4) return [] nums.sort((a, b) => a - b) const res: number[][] = [] for (let i = 0; i < len - 3; i++) { if (nums[i] > target && nums[i] > 0 && target > 0) break if (i > 0 && nums[i] === nums[i - 1]) continue for (let j = i + 1; j < len - 2; j++) { if (nums[i] + nums[j] > target && nums[i] + nums[j] > 0 && target > 0) break if (j > i + 1 && nums[j] === nums[j - 1]) continue let left = j + 1, right = len - 1 while (left < right) { const sum = nums[i] + nums[j] + nums[left] + nums[right] if (sum < target) left++ else if (sum > target) right-- else { 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-- } } } } return res }
|