[Leetcode] [Python]15:3sum

Source: Internet
Author: User

#-*-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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.