给你一个包含 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] 输出:[]
思路: 排序,双指针
class Solution:def threeSum(self, nums: List[int]) -> List[List[int]]:# 先排序nums.sort()n=len(nums)res=[]for first in range(n):# 跳过重复数if first>0 and nums[first]==nums[first-1]: continuethird=n-1target=-nums[first]for second in range(first+1,n):if second>first+1 and nums[second]==nums[second-1]:continue# 固定第二个数,遍历第三个while second<third and nums[second]+nums[third]>target:third-=1if second==third:breakif nums[second]+nums[third]==target:res.append([nums[first],nums[second],nums[third]])return res
