[Leetcode] 15. 3Sum Java

Source: Internet
Author: User

Title: 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: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]]

Test instructions and Analysis:

The idea of seeking 3Sum is as follows:

    • First, the whole sequence.
    • It then iterates through the array, pinning an element, and 2Sum to the subsequent element.

For example, after the order of the number is a B c D E F, then the first fixed a, in the remaining B C D E F 2sum, after the second enumeration B, only need to be in C D E F 2sum, so that the duplication is avoided.

 Public classSolution { PublicList<list<integer>> Threesum (int[] nums) {List<List<Integer>> res=NewArraylist<>(); if(Nums = =NULL|| Nums.length < 3)returnRes;        Arrays.sort (Nums); intn=nums.length;  for(inti=0;i<n-2;i++){            if(i > 0 && nums[i] = = Nums[i-1])Continue; inta=-Nums[i]; intLeft=i+1; intRight=n-1;  while(left<Right ) {                if((Nums[left]+nums[right]) >a) { Right--; }Else if((Nums[left]+nums[right]) <a) { Left++; }Else{List<Integer> tmp=NewArraylist<integer>();                    Tmp.add (Nums[i]);                    Tmp.add (Nums[left]);                    Tmp.add (Nums[right]);  while(Left < right && nums[left] = = nums[left+1]) left++;  while(Left < right && nums[right] = = Nums[right-1]) right--; Left++; Right--;                Res.add (TMP);            }; }        }        returnRes; }}

[Leetcode] 15. 3Sum Java

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.