题目
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
题目要求
在一个给定数组nums中找到所有满足a+b+c=0的不重复的三元组
解题思路
解题思路参照南郭子綦
先给数组排序,对于数组中的每个数nums[i],在i到len(nums)找到和为-nums[i]的两个数。因为要求不能有重复,所以实现过程中有多处地方需要注意防止重复。
- 在遍历nums时,相同的num只在第一次进行target寻找操作
- 在left和right指针移动时,如果移动到的位置与前一个位置的值相同,则继续向下移动
代码
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
ans = []
for i in range(len(nums) - 2):
if i == 0 or nums[i] > nums[i - 1]:
target = -nums[i]
left,right = i + 1,len(nums) - 1
while left < right:
if nums[left] + nums[right] == target:
ans.append((nums[i],nums[left],nums[right]))
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:left +=1
while left < right and nums[right] == nums[right + 1]:right -=1
elif nums[left] + nums[right] < target:
left += 1
while left < right and nums[left] == nums[left -1]:left += 1
else:
right -= 1
while left < right and nums[right] == nums[right + 1]:right -= 1
return ans