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