Leetcode (3Sum)

Source: Internet
Author: User

This problem gives you an array that finds all three numbers that are equal to 0 and coexist in the list. Brute-force search would probably cost O (n^3) time, but if the array was ordered, it would be relatively simple to search, and the order would probably cost O (Nlog (n)) time, and ordered searches would only cost O (n^2), so the idea was this:

    1. Sorted first.
    2. Outer Loop I record the first number, the inner loop uses 2 pointer method, when Sum>0,tail moves left, sum < 0,head move right.
    3. When you encounter sum = Nums[i] + Nums[head] + Nums[tail], save three digits to the list and save the list to the outermost list2.
    4. Pay attention to the number repetition, I use the hashset to solve.

The code is as follows:

  

1  Public classSolution {2      PublicList<list<integer>> Threesum (int[] nums) {3List<list<integer>> List =NewArraylist<list<integer>>();4Set<integer> set =NewHashset<integer>();5         //Sort6 Arrays.sort (nums);7          for(inti = 0; i < nums.length-2; i++) {8             //judged there was no repetition. 9             if(!set.add (Nums[i]))Continue;Ten             //if Nums[i] is greater than 0, there is no need to judge again . One             if(Nums[i] > 0) Break; A             intHead = i+1; -             intTail = nums.length-1; -             intLast =Nums[head]; the              while(Head <tail) { -                 if(Head! = i+1 && Nums[head] = =Last ) { -head++; -                     Continue; +                 } -                 intsum = Nums[i] + Nums[head] +Nums[tail]; +                 if(Sum > 0) tail--; A                 Else if(Sum < 0) { atLast =Nums[head]; -head++; -                 } -                 Else { -List<integer> arrayList =NewArraylist<integer>(); - Arraylist.add (Nums[i]); in Arraylist.add (Nums[head]); - Arraylist.add (Nums[tail]); to List.add (arrayList); +Last =Nums[head]; -head++; thetail--; *                 } $             }Panax Notoginseng         } -         returnlist; the     } +}

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.