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)