题目描述:
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: 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排序,然后再循环时候,同时看两个数字,一个是i+1,一个是len(nums)-1。判断三个数加和是否等于0,如果为0,把这三个数加入列表里。结果大于0说明右面的值大了,应该向左移;否则向右移。
最后注意处理下重复元素。
我的答案:
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort() # 排序
if len(nums) < 3: # 长度小于3的时候,直接返回[]
return []
if nums[-1] == 0 and nums[0] == 0: # 对于整个列表都为0的情况,排序后首位判断都为0的话,直接输出[[0, 0, 0]]
return [[0, 0, 0]]
for i in range(len(nums) - 2): # 除掉最后两位进行循环。
j = i + 1
k = len(nums) - 1
while j < k:
ans = nums[i] + nums[j] + nums[k]
if ans == 0:
res.append((nums[i], nums[j], nums[k]))
if ans > 0: # 结果大于0说明右面的值大了,应该向左移
k -= 1
else: # 结果小于0说明左面的值大了,应该向右移
j += 1
return list(set(res)) # set()用来去重,再重新变成list
学到:
- set()方法用来去重很好用。再记得转换成list
list(set(res))
- 一些特殊情况要特殊处理。
- 列表里还可以直接append一个元组。
res.append((nums[i], nums[j], nums[k]))