Two-point lookup to determine Lower_bound and Upper_bound

Source: Internet
Author: User

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

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.