Leetcode oj:search Insert Position (find insertion position)

Source: Internet
Author: User

The first line is a more stupid way, probably didn't think very carefully at that time, the general idea is to put the elements of the vector into set (because the set is inserted in the order of the time), first find, can not find the words in the insertion, the weapon noted the insertion position, When the pointer increments to that place, it finds that position. If you find the location for the first time, you can find the location directly, the code is not elegant:

1 classSolution {2  Public:3     intSearchinsert (vector<int>& Nums,inttarget) {4         Set<int>tmpset (Nums.begin (), Nums.end ());//because the set is already sorted, set5         inti =0;6         Set<int>:: iterator sitor;7         if(Sitor = (Tmpset.find (target)) = = = Tmpset.end ())//if it is not in set, insert it first .8Sitor =Tmpset.insert (target);9          for(Auto Itor = Tmpset.begin (); Itor! = It.first; + +itor) {Teni++;  One         returni; A     } -};

But actually on the internet to find a good answer, in fact, this is the dichotomy of a small deformation just:

1 classSolution {2  Public:3     intSearchinsert (vector<int>& Nums,inttarget) {4         intBeg =0;5         intEnd = Nums.size ()-1;6         intmid;7          while(Beg <=end) {8Mid = (beg + end) >>1;9             if(Nums[mid] >target)TenEnd = Mid-1; One             Else if(Nums[mid] <target) ABeg = mid +1; -             Else -                 returnmid; the         } -         intSZ =nums.size (); -         if(End <0) reutrn0;//This place should be careful, don't be wrong. -         if(Beg >=sz) reutrn sz; +         returnBeg//This step should be noted, very critical +     } A};

Dichotomy is not to be underestimated, the details are many, look carefully can have no harvest. In fact, it is not easy to write a mistake or the way it is written above.

Leetcode oj:search Insert Position (find insertion position)

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.