要求
给你一个包含 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()
l = len(nums)
res = []
for i,a in enumerate(nums):
if i == 0 or nums[i] > nums[i - 1]:
left,right = i + 1,len(nums) - 1
while left < right:
s = a + nums[left] + nums[right]
if s == 0:
tmp = [a,nums[left],nums[right]]
res.append(tmp)
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while right > left and nums[right] == nums[right + 1]:
right -= 1
elif s < 0:
left += 1
elif s > 0:
right -= 1
return res
解题思路:我们使用双指针的方式解决此题,暴力法~三重循环超时,我们先循环固定第一个值,然后在右侧的值中,取左右两端的数字,注意下,这里我们在循环的时候当出现相同值的时候,可以直接过滤掉,加速整个的时间。