Lower_bound when Target is present, returns the first position it appears in, and if it does not, returns a subscript I: The sequence is still ordered after the target is inserted here.
The code is as follows:
intLower_bound (int* Nums,intNumssize,inttarget) { //Note that the initial value of left and right must be left = 0, and right = Numsszie, because the insertion position may be [0,numssize] intleft =0; intright =numssize; intmid; while(Left <Right ) {Mid= left + (right-left)/2; if(Nums[mid] >=target) right=mid; Else Left= Mid +1; } returnLeft ;}
Although the lookup interval is [0, Numssize], the return value range is [0, Numssize]. So the initial value of right must be numssize, not numsSize-1.
When nums[mid] = = target, at least one has been found, and the left side may be there, so the interval changes to [Ieft, mid];
When Nums[mid] > target, the position cannot be in the back, but it may be mid, so the interval changes to [left, mid];
When Nums[mid] < target, mid and front are not feasible, so the range is [Mid+1, right].
To merge, when Nums[mid] >= target, the interval is [left, mid]; when Nums[mid] < target, the interval is [mid + 1, right].
Similarly, you can write a upper_bound program that, when Target is present, returns the last position in the final position where it appears, and if it does not, returns a subscript I: After the target is inserted here, the sequence remains orderly.
intUpper_bound (int* Nums,intNumssize,inttarget) { //Note that the initial value of left and right must be left = 0, and right = Numsszie, because the insertion position may be [0,numssize] intleft =0; intright =numssize; intmid; while(Left <Right ) {Mid= left + (right-left)/2; if(Nums[mid] <=target) left= Mid +1; Else Right=mid; } returnLeft ;}
Two-point lookup to determine Lower_bound and Upper_bound