The sum of the 15th question three of Leecode array

Source: Internet
Author: User

title : Three number of the sum

content :

Given an array of n integers nums , determine nums if there are three elements , a ,B, C, to make A + a + c = 0? Find all the triples that meet the criteria and do not repeat.

Note: The answer cannot contain duplicate triples.

For example, given array nums = [-1, 0, 1, 2,-1,-4], the set of triples that meet the requirements are: [  [-1, 0, 1],  [-1,-1, 2]]  ideas :
The topic realization can be divided into two steps, namely (1) Looking for three elements satisfying the condition (2) to repeat
For the first small problem, consider three for loops first, and look directly for a
1. First digit (NUM1) selection range 1~n
2. Second digit (NUM2) selection range Num1+1~n
3. Third digit (NUM3) selection range Num2+1~n
The code is as follows:
1 //looking for three numbers and 0 of the number of C + +2vector<int> Vec (3);3UnsignedintNUM1 =0, num2 =0, num3 =0;4              for(NUM1; num1 < Nums.size ()-2; num1++){5                  for(num2 = Num1 +1; Num2 < Nums.size ()-1; num2++){6                      for(num3 = num2 +1; num3 < Nums.size (); num3++){7                         if(NUMS[NUM1] + nums[num2] + nums[num3] = =0){8vec[0] =NUMS[NUM1];9vec[1] =nums[num2];Tenvec[2] =NUMS[NUM3]; One Vecs.push_back (VEC); A                         } -                     } -                 } the}

Second small problem to repeat

C + + STL provides a unique de-weight algorithm, directly to the weight can

1. Before looking for three numbers that meet the criteria, sort them to prevent the same vec from repeating because of the internal element order, such as [three-way] and [2,1,3] will be judged not to repeat

2. For vecs results to go to heavy, go to the weight before must be sorted again, because the unique function is only compared to the adjacent two elements are duplicates, if the repetition will be repeated to the tail, if the order is unlimited, for vecs[[1,2,3],[0,0,0],[1,2,3]], Because the adjacent elements do not want to wait ([1,2,3]≠[0,0,0]), the system will fail

The de-weight code is as follows:

1 // first sort, easy to go heavy 2             Sort (nums.begin (), Nums.end ()); 3 // search for three number codes that meet the criteria omitted ....  4// go to weight 5            sort (vecs.begin (), Vecs.end ()); 6             vecs.erase (Unique (Vecs.begin (), Vecs.end ()), Vecs.end ()); 7 8             return VECs;

In addition, consider the exception case, when the incoming array length is less than 3 o'clock, unable to give the solution satisfies the condition, should return empty container

The complete code is as follows:

1vector<vector<int>> Threesum (vector<int>&nums) {2vector<vector<int>>VECs;3             //Anomaly Judgment4             if(Nums.size () <3)5                 returnVECs;6 7             //first sort, easy to go heavy8 sort (Nums.begin (), Nums.end ());9 Ten             //looking for three numbers and 0 of the number Onevector<int> Vec (3); AUnsignedintNUM1 =0, num2 =0, num3 =0; -              for(NUM1; num1 < Nums.size ()-2; num1++){ -                  for(num2 = Num1 +1; Num2 < Nums.size ()-1; num2++){ the                      for(num3 = num2 +1; num3 < Nums.size (); num3++){ -                         if(NUMS[NUM1] + nums[num2] + nums[num3] = =0){ -vec[0] =NUMS[NUM1]; -vec[1] =nums[num2]; +vec[2] =NUMS[NUM3]; - Vecs.push_back (VEC); +                         } A                     } at                 } -             } -  -             //Go heavy - sort (Vecs.begin (), Vecs.end ()); - vecs.erase (Unique (Vecs.begin (), Vecs.end ()), Vecs.end ()); in  -             returnVECs; to}

For shorter inputs, you can give the appropriate results, and then for large arrays, the system prompts for too long, so you need to optimize the code.

According to the conditions given in the topic, it can be seen that the sum of three numbers is fixed, so when we select the first number NUM1, the problem becomes the two numbers for the search and for the 0-NUM1.

It can be observed that because the array is ordered, we can set two pointers to pick from both sides simultaneously

1 intTargetsum =0-NUMS[NUM1];2              while(Pleft <pright) {3                 intsum = Nums[pleft] +Nums[pright];4                 if(Sum > Targetsum | | nums[pright] = = nums[pright-1]){5pright--;6                 }7                 Else if(Sum < Targetsum | | nums[pleft] = = Nums[pleft-1]){8pleft++;9                 }Ten                 Else{ Onevec[0] =NUMS[NUM1]; Avec[1] =Nums[pleft]; -vec[2] =Nums[pright]; - Vecs.push_back (VEC); thepleft++; -pright--; -                 } -}

Also because the array is sorted, in order for if the first number we select is greater than 0, then the latter two must be greater than 0, can jump out of the loop

For repeated numbers, we can choose to skip the

The complete code is as follows:

1vector<vector<int>> Threesum (vector<int>&nums) {2vector<vector<int>>VECs;3         //Anomaly Judgment4         if(Nums.size () <3)5             returnVECs;6 7         //first sort, easy to go heavy8 sort (Nums.begin (), Nums.end ());9         Ten         //looking for three numbers and 0 of the number Onevector<int> Vec (3); AUnsignedintNUM1 =0, num2 =0, num3 =0; -          for(NUM1; num1 < Nums.size ()-2; num1++){ -             if(NUMS[NUM1] *3>0)//arrays are sorted from small to large the                  Break; -             if(NUM1! =0&& NUMS[NUM1] = = NUMS[NUM1-1]) -                 Continue; -  +             intPleft, pright; -Pleft = num1+1; +Pright = Nums.size ()-1; A              at             intTargetsum =0-NUMS[NUM1]; -              while(Pleft <pright) { -                 intsum = Nums[pleft] +Nums[pright]; -                 if(Sum > Targetsum | | nums[pright] = = nums[pright-1]){ -pright--; -                 } in                 Else if(Sum < Targetsum | | nums[pleft] = = Nums[pleft-1]){ -pleft++; to                 } +                 Else{ -vec[0] =NUMS[NUM1]; thevec[1] =Nums[pleft]; *vec[2] =Nums[pright]; $ Vecs.push_back (VEC);Panax Notoginsengpleft++; -pright--; the                 } +             } A         } the  +         //Go heavy - sort (Vecs.begin (), Vecs.end ()); $ vecs.erase (Unique (Vecs.begin (), Vecs.end ()), Vecs.end ()); $  -  -         returnVECs; the}

For complex test cases the run time is 60ms, through the topic!



The sum of the 15th question three of Leecode array

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.