给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
方法一:直接循环,复杂度高到天际。O(n^3)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums)<3:
return []
nums.sort()
s = len(nums)
l = []
for i in range(s-2):
for j in range(i+1,s-1):
for k in range(j+1,s):
if nums[i]+nums[j]+nums[k] == 0:
l.append((nums[i],nums[j],nums[k]))
reList = list(set(tuple(t) for t in l)) # 去重
reList = [list(v) for v in reList]
return reList
方法二:
想法:同两数之和。a+b=(-c)。再加一层(-c)的循环。O(n^2)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
nums.sort()
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:
ident = nums[left] + nums[right] + nums[i]
if ident == 0:
ans.append([nums[i],nums[left],nums[right]])
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 ident<0:
left += 1
else:
right -= 1
return ans