题目:
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]
]
题意:从一个数组中找到三个数,使这三个数的和为0。有可能存在多组解,也有可能存在重复的解,所以需要去重。比如:num=[-1,0,1,2,-1,-4];那么存在两组解:[[-1,0,1],[-1,-1,2]],解中的数需要是从小到大排序状态。
解题思路:1,先将数组排序。
2,排序后,可以按照TwoSum的思路来解题。怎么解呢?可以将num[i]的相反数即-num[i]作为target,然后从i+1到len(num)-1的数组元素中寻找两个数使它们的和为-num[i]就可以了。下标i的范围是从0到len(num)-3。
3,这个过程要注意去重。
4,时间复杂度为O(N^2)。
方法一:1848ms
class Solution(object):
def threeSum(self, nums):
nums.sort()
res = []
for i in range(len(nums) - 2):
if i == 0 or nums[i] > nums[i - 1]:
left = i + 1
right = len(nums) - 1
while left < right:
if nums[left] + nums[i] + nums[right] == 0:
res.append([nums[left], nums[right], nums[i]])
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[i] + nums[right] < 0:
while left < right:
left += 1
if nums[left] > nums[left - 1]: break
else:
while left < right:
right -= 1
if nums[right] < nums[right + 1]: break
return res
方法二:1459ms
这个方法和方法一本质一样
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums)
nums.sort()
res = set()
for i in range(0, n - 2):
if i and nums[i] == nums[i - 1]:
continue
l, r = i + 1, n - 1
while l < r:
x = nums[i] + nums[l] + nums[r]
if x == 0:
res.add((nums[i], nums[l], nums[r]))
l += 1
r -= 1
while l < r and nums[l] == nums[l - 1]:
l += 1
while l < r and nums[r] == nums[r + 1]:
r -= 1
elif x < 0:
l += 1
else:
r -= 1
return [list(x) for x in res]
方法三:839ms
和前两个方法的区别,就是for循环和while的区别
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums)
nums.sort()
sol = []
i = 0
while i < n-2:
if nums[i] > 0:
break
j = i+1; k = n-1
while j < k:
s = nums[i] + nums[j] + nums[k]
if s == 0:
sol.append([nums[i],nums[j],nums[k]])
j += 1; k -= 1
while j < k and nums[j] == nums[j-1]:
j += 1
while j < k and nums[k] == nums[k+1]:
k -= 1
elif s < 0:
j += 1
p = -nums[i]-nums[k]
while j < k and nums[j] < p:
j += 1
else:
k -= 1
q = -nums[i]-nums[j]
while j < k and nums[k] > q:
k -= 1
i += 1
while nums[i] == nums[i-1] and i < n-2:
i += 1
return sol
方法四:639ms
这个方法效率最高,使用了字典,仍旧是两层循环嵌套,优化在哪儿了?
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ct = {}
ret = []
for n in nums:
ct[n] = ct.get(n,0) + 1
uniques = ct.keys()
pos = [s for s in uniques if s >= 0]
neg = [s for s in uniques if s < 0]
pos.sort()
neg.sort(reverse=True)
if ct.get(0,0) >= 3:
ret.append([0,0,0])
for p in pos:
for n in neg:
r = 0-p-n
if (r == p or r == n) and ct[r] > 1:
ret.append([p,n,r])
elif r in ct and (r > p or r < n):
ret.append([p,n,r])
return ret