1.题目:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
2.代码:
/*
对于算法跳过i,m,n重复部分:
0 1 2 3 4 5 6 7 8 9
-2, -2, -2, 0, 0, 0, 1, 1, 3, 4
1.对于i跳过相同元素:
必须的,不然会出现重复序列
2.对于m,n跳过相同元素:
若要重复部分最后一个:
0 1 2 3 4 5 6 7 8 9
-2, -2, -2, 0, 0, 0, 1, 1, 3, 4
i,m,n:没有0,6,7和3,4,5,只有0,1,9
所以m,n选择各自方向上第一个,即
m==m-1=>m++
n==n+1=>n--
*/
- 遍历+两数之和:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
r = []
nums.sort()
lens = len(nums)
for i in range(lens):
if i>0 and nums[i]==nums[i-1]:
continue
if nums[i]>0:
return r
m = i+1
n = lens-1
while m<n:
if nums[m]+nums[n]> -nums[i]:
n = n-1
elif nums[m]+nums[n]< -nums[i]:
m = m+1
else:
# print(i,m,n)
t = [nums[i],nums[m],nums[n]]
r.append(t)
m = m+1
n = n-1
while m<lens and nums[m] == nums[m-1]:
m = m+1
while n>i and nums[n] == nums[n+1]:
n = n-1
return r
- 对情况进行分类⇒ (3,0),(2,1),(1,1,1),(1,2),其中数字是相同的个数:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
r = []
counts = {}
for i in nums:
counts[i] = counts.get(i, 0) + 1
nums = sorted(counts)
lens = len(nums)
for i,num in enumerate(nums):
if counts[num]>1:
#3,0
if num ==0 and counts[num]>2:
r.append([0,0,0])
#2,1
elif -2*num in nums and num!=0:
# if num>0:
# r.append([-2*num,num,num])
# else:
r.append([num,num,-2*num])
#1,1,1
#1,2
if num<0:
m,n = i+1,len(nums)-1
while m<n:
if nums[m]+nums[n]>-nums[i]:
n = n-1
elif nums[m]+nums[n]<-nums[i]:
m = m+1
else:
r.append([num,nums[m],nums[n]])
n = n-1
m = m+1
return r