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(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n=len(nums)
nums.sort()
final_list=[]
for i in range(0, n-1):
l = i + 1
r = n - 1
x = nums[i]
if x>0:
break
if (i>0 and nums[i]==nums[i-1]):
continue
while (l < r):
# x 是最小的
if (x + nums[l] + nums[r] == 0):
final_list.append( [x, nums[l], nums[r]])
while (l < r and nums[l]==nums[l+1]):
l+=1
while (l < r and nums[r]==nums[r-1]):
r-=1
l+=1
r-=1
found = True
# If sum of three elements is less
# than zero then increment in left
elif (x + nums[l] + nums[r] < 0):
l+=1
# if sum is greater than zero than
# decrement in right side
else:
r-=1
return final_list
# 反思 首先习惯了sort, 然后排除重复花了很长时间,注意用while 排除多个重复,然后一旦用while还有再次check初始条件是不是被这次循环打破,非常不elegent。
大神:
from collections import Counter
class Solution(object):
def threeSum(self, nums):
if len(nums) <= 2:
return []
counter = collections.Counter(nums)
print(counter)
res = []
if counter[0] >= 3:
res.append([0, 0, 0])
neg = []
pos = []
for x in counter:
if x < 0:
neg.append(x)
for x in counter:
if x >= 0:
pos.append(x)
for n in neg:
for p in pos:
x = 0 - (n + p)
if x in counter:
if x in {n, p} and counter[x] >= 2:
res.append([n,x,p])
if x < n:
res.append([n,x,p])
if x > p:
res.append([n,x,p])
return res
```
# 反思
大神用来count来生成字典 ,还顺便去了重,字典的效率就很高了,求相反数 。