这题难度为中等,目前通过率为21.8%
题目:
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]
]
题目大意是找到这n个整数中所有的三个整数和为0的组合。
思路:
对列表进行排序,然后对每个数找另外两个数进行匹配。
步骤:
1.每次选定一个数,判断这个数是否和前一个相同,如果相同说明已经经过计算,则计算下一个以避免浪费时间
PS:由于python的特性,如果位置为负数则从列表后面找,这样对于0号位置的数容易发生错误。例子:[0,0,0]
2.对后面每个数,由于列表是从小到大有序的,所以可以进行夹逼找到和为0的数。如果和小于0,则把左边值往右移,如果大于0,则把右边值往左移。如果等于0,则找到一个答案,加到列表res中,并更新左边值和右边值。
代码:
class Solution:
def threeSum(self, nums):
res = []
nums.sort()
n = len(nums)
for i in range(n-2):
if nums[i] == nums[i-1] and i > 0:
continue
l,r = i+1,n-1
while l<r:
s = nums[i]+nums[l]+nums[r]
if s<0:
l += 1
elif s>0:
r -= 1
else:
res.append([nums[i],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
return res
复杂度分析:
外层一个for循环,循环(n-2)次,内层每次找数,最坏情况下要从位置1找到(n-1),需要(n-2)次,因此时间复杂度为
T(n) = (n-2)*(n-2) = O(n^2)
提交: