题目
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],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
题意
题目其实还蛮清楚的,给出一个数组然后找出里面3元素组合满足3元素相加结果为0,要求这个元素组合都是唯一的,难点有几个,一个是要求唯一,因为返回的是一个list,但是其实它的结果要求是[0,1,-1]和[1,-1,0]都是同一个,另外一个是时间复杂度的要求,贸贸然交很容易超时。。。如果N^3的话;
想法
对于第一个问题要求结果唯一,当时是个想法,就是直接生成的结果是排过序的,比如说[min,0-min,max],然后最后对结果先取一遍set再转List就行了,但这个想法后来受第二个问题的影响,推翻掉了,或者说避免掉了。
其实这道题是2SUM的变形,如果a+b+c=0,你固定了a,要求b+c=-a就行了,我之前也是这个想法但是一直超时:先固定a,然后去遍历b,在b所在下标和数组结尾间二分查找,中间穿插一些去重操作,理论是可行的后来一直超时,拿最长的样例去测发现差很多;后来才知道这是一个2SUM变形,先做完排序,然后固定a后就可以用O(n)的复杂度找出组合了,我之前是需要O(nlogn)那样子,因为我还做了一遍二分搜索。。。
所以最后的做法是:先固定a,然后在剩下的数组里面完成2SUM的计算,需要注意的是它要求不重复,那就是a用完一个数后移动到下一个不重复的数,同理,b用完一个数后也移动到下一个不重复的数;
最后再提一下的是交上去的排名,之前很差,只有13%差不多,然后我加了一个操作,让a遍历的范围从负数到第一个非负数,上去了一些到30%几,然后又把一个a,即读数组中的某个位置的结果存了一下,后面的运行比如说判断a+b+c时就可以由num[idx_a] + num[idx_b] + num[idx_c]变成了 a+num[idx_b] +num[idx_c],一下子就到90%了。所以就是重复的一些无谓操作就保存中间结果,当计算次数较多时可以节省很大一部分运行时间。
参考代码
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
solution = list()
for i in range(len(nums)):
if nums[i]>0:
break
if i>0 and nums[i]==nums[i-1]:
continue
beginidx = i+1
endidx = len(nums)-1
target = nums[i]
while beginidx<endidx and nums[endidx]>=0:
result = target+nums[beginidx]+nums[endidx]
if result==0:
solution.append([target,nums[beginidx],nums[endidx]])
while beginidx+1<endidx and nums[beginidx]==nums[beginidx+1]:
beginidx +=1
while beginidx<endidx-1 and nums[endidx]==nums[endidx-1]:
endidx -=1
beginidx += 1
endidx -= 1
elif result>0:
endidx-=1
else:
beginidx+=1
return solution