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