#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
15:3sum
https://oj.leetcode.com/problems/3sum/
Given an array S of n integers, is 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.
Note:
Elements in a triplet (A,B,C) must is in non-descending order. (ie, a≤b≤c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2-1-4},
A Solution set is:
(-1, 0, 1)
(-1,-1, 2)
===comments by dabay===
First sort, then fixed a number from left to right, in the back of the series using the left hand pointer toward the middle of the method to find.
A number is fixed from left to right (if the number you want to judge is skipped with the previous equality),
Around two hands to the middle of the time, can be guaranteed not to miss. (If a set of data is found, the left pointer continues to move to the next number of unequal numbers)
‘‘‘
Class Solution:
# @return A list of lists of length 3, [[Val1,val2,val3]]
def threesum (self, num):
If Len (num) < 3:
return []
Num.sort ()
res = []
For i in xrange (Len (num)-2):
If I>0 and Num[i]==num[i-1]:
Continue
target = 0-num[i]
J, k = i+1, Len (num)-1
While J < k:
If NUM[J] + num[k] = = target:
Res.append ([Num[i], num[j], num[k])
j = j + 1
While J<k and Num[j]==num[j-1]:
j = j + 1
Elif Num[j] + num[k] < target:
j = j + 1
Else
K = K-1
return res
def main ():
Sol = solution ()
Nums = [0,0,0,0,0]
Solutions = Sol.threesum (nums)
For solution in Solutions:
Print Solution
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]15:3sum