3Sum (look for the sum of three numbers for the set of the specified number of medium)

Source: Internet
Author: User

Topic meaning: Give a random ordinal group, in which look for all cases of three numbers and for 0, these conditions cannot be repeated, ascending order

Idea: The front 2sum, I use a map, natural that the problem map is more efficient than the double pointer, the problem needs to be sorted first, and then give three pointers, I, J, K

For the I pointer is traversed backwards, for a fixed I pointer, in fact, is the case of 2Sum, given a previous two pointers to traverse,

When the value is large, move the back of the pointer forward, the value is small, and move the front pointer backward.

The trouble is to go to the heavy, first of all I pointer to the weight, J and K only with a weight to be able to

PS: This is a very common method in arrays.

1 classSolution {2  Public:3vector<vector<int>> Threesum (vector<int>&nums) {4vector<vector<int>>ans;5vector<int> Temp (3);6         intSize=nums.size ();7         intj,k;8 sort (Nums.begin (), Nums.end ());9          for(intI=0; i<size-2;++i) {// Note This position can be written nums.size (), Just can't write Nums.size ()-2, what's the reason I haven't figured it out yet. Ten             //while (i>0&&nums[i]==nums[i-1]) ++i; Pay attention to comparing two ways of writing One             if(i>0&&nums[i]==nums[i-1])Continue; Aj=i+1; -k=size-1; -              while(j<k) { the                 if(j>i+1&&nums[j]==nums[j-1]){ -++J; -                     Continue; -                 } +                 if(Nums[j]+nums[k]>-nums[i])--K; -                 Else if(Nums[j]+nums[k]<-nums[i]) + +J; +                 Else{ Atemp[0]=Nums[i]; attemp[1]=Nums[j]; -temp[2]=Nums[k]; - Ans.push_back (temp); -++J; ---K; -                 } in             } -         } to         returnans; +     } -};

Complexity: O (n2)

3Sum (look for the sum of three numbers for the set of the specified number of medium)

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.