题目
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
代码
class Solution:
def threeSum(self, nums):
res = []
nums.sort() # 首先做排序
for i in range(len(nums)-2):
if nums[i] > 0: # 如果nums[i]大于0,则三数和total必定>0,结束循环
break
if i>0 and nums[i]==nums[i-1]: # 如果有重复nums[i],进入下一个循环,避免重复
continue
left, right = i+1, len(nums)-1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0: # 若total<0,说明三数和小了,需要加数字,故left右移
left += 1
elif total > 0: # 若total>0,说明三数和大了,需要减数字,故right左移
right -= 1
else:
res.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]: # 查看left后是否有重复数字,有则跳过
left += 1
while left < right and nums[right] == nums[right-1]: # 查看right前是否有重复数字,有则跳过
right -= 1
left += 1
right -= 1
return res