Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Example
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:
(-1, 0, 1)
(-1, -1, 2)
Note
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
Solution
Time: O(N2), Space O(N)
12345678
S = {-1 0 1 2 -1 -4}
排序后:
S = {-4 -1 -1 0 1 2}
↑ ↑ ↑
i j k
→ ←
i每轮只走一步,j和k根据S[i]+S[j]+S[k]=ans和0的关系进行移动,且j只向后走(即S[j]只增大),k只向前走(即S[k]只减小)
如果ans>0说明S[k]过大,k向前移;如果ans<0说明S[j]过小,j向后移;ans==0即为所求。
classSolution:""" @param numbersbers : Give an array numbersbers of n integer @return : Find all unique triplets in the array which gives the sum of zero. """defthreeSum(self,numbers):# write your code hereresult=[]iflen(numbers)<3:returnresultsorted_array=sorted(numbers)# a[i] is the first one# a[j] is the middle one# a[k] is the last oneforiinrange(len(sorted_array)):j=i+1k=len(sorted_array)-1whilej<k:ifsorted_array[i]+sorted_array[k]+sorted_array[j]>0:k-=1elifsorted_array[i]+sorted_array[k]+sorted_array[j]<0:j+=1else:# found the target# if not duplicated, append it.if[sorted_array[i],sorted_array[j],sorted_array[k]]notinresult:result.append([sorted_array[i],sorted_array[j],sorted_array[k]])# move j to next unduplicated posifsorted_array[j]!=sorted_array[j+1]:j+=1else:whilej<len(sorted_array)-1andsorted_array[j]==sorted_array[j+1]:j+=1# move k to next unduplicated posifsorted_array[k]!=sorted_array[k-1]:k-=1else:whilek>0andsorted_array[k]==sorted_array[k-1]:k-=1returnresult