LeetCode Medium:15. 3Sum
一、题目
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example: Given array nums = [-1, 0, 1, 2, -1, -4], outout =[[-1,0,1],[-1,-1,2]]
给定一个数组,找出数组中的三个数字组合,使其相加等于0,返回一个list集合,并且要求list集合中的组合数不重复
二、思路
此问题与 two Sum 的情况类似,可以将 three Sum问题转换成 two Sum问题,步骤如下:
1、对给定的数组进行排序,得到 newnums;
2、遍历newnums的前 n - 3项,定义两个指针,分别指向当前数字的下一个元素,和 newnums 的最后一个元素;
3、循环判断条件设置为头指针索引小于尾指针索引时,一直循环
上面是大的框架,还有几点注意的细节,比如给定的数组长度小于3,则返回空;当前的数字如果和前一个数字相同则跳过,这样的话,其实就已经避免了最后的 list 集合重复,所以最后不用加以判断 list 重复,见代码部分,注释掉的部分如果写在程序里的话会超时,注释掉的话,则AC。
三、代码
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums)<3:
return []
list_sums = []
newnums = sorted(nums)
for point1 in range(len(newnums)-2):
list_sum = []
point2 = point1 + 1
point3 = len(newnums)-1
if newnums[point1] > 0 or newnums[point3]<0:
break
if point1>0 and newnums[point1] == newnums[point1 - 1]:
continue
while point2 < point3:
a = sum([newnums[point1], newnums[point2], newnums[point3]])
if a > 0:
point3-=1
elif a < 0:
point2+=1
else:
list_sum=[newnums[point1],newnums[point2],newnums[point3]]
"""
由于前后对point1,point2,point3均作了判断,如果重复就跳过,所以这里生成的list_sum
不可能有重复的,顾这段代码可以省略,省略之后能AC,否则NA
"""
# if list_sum not in list_sums:
# print(list_sum)
# list_sums.append(list_sum)
list_sums.append(list_sum)
point2+=1
point3-=1
while point2<point3 and newnums[point2]==newnums[point2-1]:
point2+=1
while point2<point3 and newnums[point3]==newnums[point3+1]:
point3-=1
#list_sum = []
#print(list_sums)
return list_sums
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
浙公网安备 33010602011771号