给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
class Solution:def threeSum(self, nums: List[int]) -> List[List[int]]:res = []n = len(nums)if not nums or n < 3:return resnums.sort()for i in range(len(nums)):if nums[0] > 0: # 都为正 return []if i > 0 and nums[i] == nums[i - 1]: # 去重continueL = i + 1 # 左指针为 i + 1R = n - 1while L < R:if nums[i] + nums[L] + nums[R] == 0:res.append([nums[i], nums[L], nums[R]])while L < R and nums[L] == nums[L + 1]:L += 1while L < R and nums[R] == nums[R - 1]:R -= 1L += 1R -= 1elif nums[i] + nums[L] + nums[R] > 0:R -= 1else:L += 1return res