15. 三数之和 - 力扣(LeetCode)
class Solution:def threeSum(self, nums: List[int]) -> List[List[int]]:nums.sort() # 排序n = len(nums)res = []for i in range(n):# 剪枝:如果当前数 > 0,三数之和不可能为 0if nums[i] > 0:break# 去重:跳过重复元素if i > 0 and nums[i] == nums[i - 1]:continue# 双指针left, right = i + 1, n - 1while left < right:total = nums[i] + nums[left] + nums[right]if total == 0:res.append([nums[i], nums[left], nums[right]])# 去重:跳过相同的 left 和 rightwhile left < right and nums[left] == nums[left + 1]:left += 1while left < right and nums[right] == nums[right - 1]:right -= 1left += 1right -= 1elif total < 0:left += 1 # 和偏小,左指针右移else:right -= 1 # 和偏大,右指针左移return res