2sum,3sum,4sum,ksum,3sum Closest series

Source: Internet
Author: User

1). 2sum

1. Test instructions: Find all pairs of numbers in the array and for target

2. Idea: Sort the array, then use two pointers I, J, one after, calculate the relationship between the contents of two pointers and target, if less than target,i right shift, if greater than, J left shift, otherwise one of the solutions

3. Time complexity: O (NLGN) +o (n)

4. Space: O (1)

5. Code:

    voidTwosum (vector<int>& Nums,intNumssize,inttarget,vector<vector<int>>&twosumres) {       inti=0,j=numssize-1;  while(i<j) {           if(Nums[i]+nums[j] <target) {i++; }Else if(Nums[i]+nums[j] >target) {J--; }Else{vector<int>Oneofres;               Oneofres.push_back (Nums[i]);               Oneofres.push_back (Nums[j]);               Twosumres.push_back (Oneofres); I++;
/* Find non-repeating pairs * / while(nums[i]==nums[i-1]) i++; J--;
/* Find non-repeating pairs * / while(nums[j]==nums[j+1]) j--; } } }

2). 3sum

1. Test instructions: Find the combination of all three numbers in the array and for target, the elements in any two combination cannot be the same, for example, target=5,2,2,1 and 1,2,2 are repeating combinations, because the elements in two combinations are identical and can only take one of them.

2. Idea: This problem can be converted to test instructions, take an array of an element A, the remainder of the element and the target-a for all the non-complex pairs, converted to 2Sum problem.

3. Time complexity: O (NLGN) +o (n*n)

4. Space: O (1)

5. Code:

classSolution { Public:    voidTwosum (vector<int>& Nums,intNumssize,intStartinttarget,vector<vector<int>>&twosumres) {       inti=start,j=numssize-1;  while(i<j) {           if(Nums[i]+nums[j] <target) {i++; }Else if(Nums[i]+nums[j] >target) {J--; }Else{vector<int>Oneofres;               Oneofres.push_back (Nums[i]);               Oneofres.push_back (Nums[j]);               Twosumres.push_back (Oneofres); I++;  while(nums[i]==nums[i-1]) i++; J--;  while(nums[j]==nums[j+1]) j--; }}} vector<vector<int>> Threesum (vector<int>&nums) {size_t nums_size=nums.size (); Vector<vector<int>>Res;        Sort (Nums.begin (), Nums.end ());  for(size_t i=0; i<nums_size;i++){            if(i>0&& (nums[i]==nums[i-1])){                Continue; }Vector<vector<int>>Twosumres; Twosum (Nums,nums_size,i+1,-nums[i],twosumres); if(!Twosumres.empty ()) {size_t J_times=twosumres.size ();  for(size_t j=0; j<j_times;j++) {Twosumres[j].insert (Twosumres[j].begin (), nums[i]);                Res.push_back (Twosumres[j]); }            }        }        returnRes; }};

3). 4sum,ksum

1. Title: The non-repeating combination of all and 4 elements of target, the elements in any two combination cannot be the same.

2. Idea: Recursion, 4sum->3sum->2sum

3. Time complexity: O (NLGN) +o (n*n*...*n), K-1 N

Code:

classSolution { Public: Vector<vector<int>> Towsum (vector<int>& Nums,intNumssize,intStartinttarget) {Vector<vector<int>>Res; inti = start,j=numssize-1;  while(i<j) {            if(Nums[i] + nums[j] <target) {i++; }Else if(Nums[i] + nums[j] >target) {J--; }Else{vector<int>item;                Item.push_back (Nums[i]);                Item.push_back (Nums[j]);                Res.push_back (item); I++;  while(nums[i]==nums[i-1]) i++; J--;  while(nums[j]==nums[j+1]) j--; }        }        returnRes; } Vector<vector<int>> Ksum (vector<int>& Nums,intNumssize,intStartintKinttarget) {        if(k==2){            returntowsum (Nums, numssize, start, target); }Else{vector<vector<int>>Ksumres;  for(size_t i=start;i<numssize;i++){                if(I>start && (nums[i]==nums[i-1])){                    Continue; } Vector<vector<int>> item = ksum (nums,numssize,i+1, K-1, target-Nums[i]); size_t itemsize=item.size ();  for(size_t j=0; j<itemsize;j++) {Item[j].insert (Item[j].begin (), nums[i]);                Ksumres.push_back (Item[j]); }            }            returnKsumres; }} vector<vector<int>> Foursum (vector<int>& Nums,inttarget)        {Sort (Nums.begin (), Nums.end ()); size_t numssize=nums.size (); returnKsum (Nums,numssize,0,4, Target); }};

4). Similar question, 3Sum Closest

1. Title:

Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.

    For example, given array S = {-1 2 1-4}, and target = 1.    The sum is closest to the target is 2. (-1 + 2 + 1 = 2).

2. Time: O (NLGN) +o (n*m*2), m*2 indicates the number of temptations

3. Code

classSolution { Public:    BOOLTwosum (vector<int>& Nums,intNumssize,intStartinttarget) {        inti=start,j=numssize-1;  while(i<j) {            if(Nums[i] + nums[j] <target) {i++; }Else if(Nums[i] + nums[j] >target) {J--; }Else{                return true; }        }        return false; }    intThreesumclosest (vector<int>& Nums,inttarget)        {Sort (Nums.begin (), Nums.end ()); size_t numssize=nums.size (); intIncreasment =0;  while(true){            BOOLHastwosum =false;  for(size_t i=0; I<nums.size (); i++) {hastwosum= Twosum (nums,numssize,i+1, target+increasment-Nums[i]); if(hastwosum) { Break; } hastwosum= Twosum (nums,numssize,i+1, target-increasment-Nums[i]); if(hastwosum) {increasment= -increasment;  Break; }            }            if(hastwosum) { Break; } increasment++; }        returntarget+increasment; }};

5). Post-post:

The algorithm prototype for this type of problem is 2Sum, in the case of non-repetition of the number of pairs, there is a small trick (on the basis of order), is to get arry[i]+arry[j] = = target, to remove the arry[i] and arry[j] equal elements.

This method of using two pointers to handle arrays is also common, for example, sorting color arrays, odd even numbers, sequential Subarray in an ordered array, all combinations of target, and so on.

2sum,3sum,4sum,ksum,3sum Closest series

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.