[Leetcode] 3Sum

Source: Internet
Author: User

1 Topics:

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)

2 Ideas:

First thought to sort. Then think of is, since to 0, then there must be a negative number (OK, can be three 0), then you need to find a positive, negative junction, and then with two pointers, a negative number, a pointer to a positive, so compared.

As a result, the code is more complex, but also a variety of special problems, such as cross-border, changed for half a day, or can not pass. Then give up and look at other people's excellent ideas.

Https://leetcode.com/discuss/23638/concise-o-n-2-java-solution

And then I found out I was dead, and the sort was definitely right, so why not start with the smallest positive number and start with the biggest positive number? This does not have to worry about 0 of the problem.

3 Code:

     PublicList<list<integer>> Threesum (int[] nums)        {Arrays.sort (nums); intLen =nums.length; List<List<Integer>> answerlist =NewArraylist<list<integer>>();  for(inti = 0; i < len-2; i++){            if(i = = 0 | | (i > 0 && nums[i]!=nums[i-1])){                    inthi = len-1; intLo = i + 1; intsum = 0-Nums[i];  while(Lo <hi) {                    if(Nums[lo] + nums[hi] = =sum)                        {Answerlist.add (Arrays.aslist (Nums[i],nums[lo],nums[hi]));  while(Lo < hi && Nums[lo] = = nums[lo+1]) lo++;  while(Lo < hi && Nums[hi] = = Nums[hi-1]) hi--; Lo++; Hi--; }Else if(Nums[lo] + Nums[hi] < sum) lo++; Elsehi--; }            }        }        returnanswerlist; }

   



[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.