给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。

示例 1:
输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = [] 输出:[]
示例 3:
输入:nums = [0] 输出:[]

思路: 排序,双指针

  1. class Solution:
  2. def threeSum(self, nums: List[int]) -> List[List[int]]:
  3. # 先排序
  4. nums.sort()
  5. n=len(nums)
  6. res=[]
  7. for first in range(n):
  8. # 跳过重复数
  9. if first>0 and nums[first]==nums[first-1]: continue
  10. third=n-1
  11. target=-nums[first]
  12. for second in range(first+1,n):
  13. if second>first+1 and nums[second]==nums[second-1]:continue
  14. # 固定第二个数,遍历第三个
  15. while second<third and nums[second]+nums[third]>target:
  16. third-=1
  17. if second==third:break
  18. if nums[second]+nums[third]==target:
  19. res.append([nums[first],nums[second],nums[third]])
  20. return res