LeedCode15:三数之和
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解题思路一:
暴力算法(不应该称之为算法):
三层循环找到符合条件的数时间复杂度为
解题思路二:
=> 申请一个一个set集合将nums中所有的元素存进去,用双层loops很容易找a
和b,再在set集合中便利找到c复杂度为 ,但是这样会多开辟一块空间。
解题思路三:
先将整个数组排序python中可以直接用sort()方法进行排序,基于快排时间复杂度为 例如nums = [-1, 0, 1, 2, -1, -4]
[-4, -1, -1 , 0, 1, 2 ]
先枚举找打a 一层loop在从剩下的元素中[-1, -1 , 0, 1, 2 ] 找b和c
因a之后的元素是有序的那么我们就可以同时头和尾开始找
假设b从头开始,c从尾开始,如果a+b+c大于零,那么c需要变小c往左移
如果a+b+c大于零,那么b需要变大b往右移
c复杂度为
完整代码:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
l,r = i+1,len(nums)-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