二分区间

#include <iostream>
using namespace std;
int lower_bound(int* a, int n, int x) {
  int l = 0, r = n - 1;
  while(l < r) {
    int mid = l + r >> 1;
    if(a[mid] >= x) r = mid;
    else l = mid + 1;
  }
  return l;
}
int upper_bound(int* a, int n, int x) {
  int l = 0, r = n - 1;
  while(l < r) {
    int mid = l + r + 1 >> 1;
    if(a[mid] <= x) l = mid;
    else r = mid - 1;
  }
  return l;
}
int main() {
  int a[] = { 1, 2, 4, 4, 5};
  int n = sizeof(a) / sizeof(a[0]), x = 4;
  cout << lower_bound(a, n, x) << " " << upper_bound(a, n, x) << endl;
  return 0;
}
posted @ 2021-02-25 16:00  SteveYu  阅读(124)  评论(0编辑  收藏  举报