给定一个整数数组nums,判断是否存在三元组[nums[i],nums[j],nums[k]]满足i!=j,i!=k,同时满足nums[i]+nums[j]+nums[k]==0。
注意:答案中不可以包含重复的三元组
方法1:暴力解法
使用三重循环,分别找出第1,2,3个元素分别判断是否和为0
空间复杂度:O(n3)
空间复杂度:O(1)
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
a=list()
l=len(nums)
for i in range(l-2):
for j in range(i+1,l-1):
for k in range(j+1,l):
if nums[i]+nums[j]+nums[k]==0:
temp = [nums[i], nums[j], nums[k]]
temp.sort() # 排序,以便比较时更容易避免重复
if temp not in a:
a.append(temp)
else:
a=a
return a
运行可以通过,提交时会超出时间限制
时间复杂度:O(n3)
空间复杂度:O(1)
方法二:排序+双指针
关键提示:不包含重复键;利用排序避免重复答案
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums) #获取数组长度
nums.sort() #数组排序
ans = list() #初始化一个空列表 ans,用于存储最终的三元组结果
# 枚举 a
for first in range(n): #使用 first变量枚举数组中每一个元素,作为三元组中的第一个数 a
# 需要和上一次枚举的数不相同,如果两个相同的元素作为第一个数,后续的解一定会重复
if first > 0 and nums[first] == nums[first - 1]:
continue #跳出循环,a指针右移
third = n - 1 ## c 对应的指针初始指向数组的最右端
target = -nums[first]
for second in range(first + 1, n):#枚举b
#需要和上一次枚举数不同,因为同一个first值对应的多个second可能会产生相同的三元组。
if second > first + 1 and nums[second] == nums[second - 1]:
continue #跳出循环,b指针右移
#保证b指针在c的指针的左侧,如果和大于目标,说明third需要向左移动来减小和。
while second < third and nums[second] + nums[third] > target:
third -= 1
# 如果指针重合,随着 b 后续的增加
# 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if second == third:
break
if nums[second] + nums[third] == target:
ans.append([nums[first], nums[second], nums[third]])
return ans
时间复杂度:O(n2)
空间复杂度:O(n)