题目:
给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
思路:
1.对数组进行遍历,然后判断0减去另外两个数是否存在于剩下数字中,超时
2.对1进行改进,不使用in,对有序的list使用双向
3.最后的结果为三种数字的组合。使用字典对数组中的数字进行统计,而后对其进行分组,可知,若要三个数字相加为0,则其中必有一正一负,以此对数组进行分组。且采用字典进行去重,无需排序,以空间换时间
1.
def threeSum(self, nums: List[int]) -> List[List[int]]:
l =[]
nums = sorted(nums)
for i in range(len(nums)-2):
if nums[i] == nums[i-1] and i!=0:
continue
for j in range(i+1,len(nums)-1):
if nums[j] == nums[j-1] and j!=i+1:
continue
if 0-nums[i]-nums[j] in nums[j+1:]:
l.append([nums[i],nums[j],0-nums[i]-nums[j]])
return l
2.将一个数固定,另外两个进行寻找时可以从有序数组的头尾进行寻找
abcde
a+e>f ->a+d <f -> b+d?如此往后
这里为什么在小时前向后移动,大尾想起移动
以上述为例b+d<f 应该为c+d,为什么不是b+e
因为a+e>f b>a
所有b+e>f
def threeSum(self, nums: List[int]) -> List[List[int]]:
lr =[]
nums = sorted(nums)
for i in range(len(nums)-2):
if i !=0 and nums[i] == nums[i-1]:
continue
l = i+1
r = len(nums)-1
while r > l:
s = nums[i]+nums[l]+nums[r]
if s == 0:
lr.append([nums[i],nums[l],nums[r]])
l+=1
r-=1
while r>l and nums[l]==nums[l-1]:
l+=1
while r>l and nums[r]==nums[r+1]:
r-=1
elif s>0:
r-=1
while r>l and nums[r]==nums[r+1]:
r-=1
else:
l+=1
while r>l and nums[l]==nums[l-1]:
l+=1
return lr
3.此方法相当于默认对数组进行了过滤,去除了三负或三正的情况,减少了循环次数
当出现[-1,-2,3]时结果会出现重复,需要进行过滤【-1,3,-2】【-2,3,-1】[i,j,k]
def threeSum(self, nums):
l = []
dic = {}
for i in nums:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
f = [i for i in dic if i < 0]
z = [i for i in dic if i > 0]
if 0 in dic and dic[0] > 2:
l.append([0,0,0])
for i in f:
for j in z:
k = 0 - i - j
if k in dic:
if k == i and dic[k] > 1:
l.append([i,j,k])
elif k == j and dic[k] > 1:
l.append([i,j,k])
elif k < i or k > j or k ==0: #进行判断去除重复排序保证k<i<j or k>j>i
l.append([i,j,k])
return l