Leetcode------3Sum

Source: Internet
Author: User

Title: 3Sum
Pass Rate: 16.9%
Difficulty: Medium

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, abc)
    • 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)

From the topic began to use Python to do the problem;

The previous one has done a 2sum with the map method, this time with a suitable and ksum aspect. Base is still 2sum

2sum is done with two pointers, the start pointer points to the beginning, the end pointer points to the end of the match,

For the 3sum is the addition of a layer of loops, starting from the 0th position, entering to 2sum is the beginning of the first

For 4sum, we're adding two layers outside of 2sum.

One analogy

The code is as follows:

1 classSolution:2     #@return A list of lists of length 3, [[Val1,val2,val3]]3     defthreesum (self, num):4 Num.sort ()5Ans = []6target=07          forIinchRange (0, Len (num)):8L, R = i + 1, len (num)-19              whileL <r:Tensum = Num[i] + num[l] +Num[r] One                 ifsum = =Target: Atmp=[Num[i], num[l], Num[r] -                     ifTmp not inchans: - ans.append (TMP) theL, R = L + 1, r-1 -                 elifSum <Target: -L = L + 1 -                 Else: +r = R-1 -         returnAns

Leetcode------3Sum

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.