标签:大于 一个 upper lap one turn microsoft 种类 存在
1、查找最后一个小于或者等于key的下标,若不存在,则返回-1 ==> 同lower_bound(arr+1, arr+1+n, key)
int BinSearch(int a[], int n, int key) { int m, l = 0, r = n - 1;//闭区间[0, n - 1] while (l <= r) { m = (l+r)/2; if (a[m] <= key) l = m + 1; else if(a[m] > key) r = m - 1; } if(l == 0) return -1;//not find return l-1; }
2、查找第一个大于或者等于key的下标,若不存在,则返回-1
int BinSearch(int a[], int n, int key) { int m, l = 0, r = n - 1;//闭区间[0, n - 1] while (l <= r) { m = (l+r)/2; if (a[m] < key) l = m + 1; else if(a[m] >= key) r = m - 1; } if(r == n-1) return -1;//not find return r+1; }
3、查找第一个与key相等的下标,若不存在,则返回-1
int BinSearch(int a[], int n, int key) { int m, l = 0, r = n - 1;//闭区间[0, n - 1] while (l < r) { m = l + ((r - l) >> 1);//向下取整 if (a[m] < key) l = m + 1; else r = m; } if (a[r] == key) return r; return -1; }
4、查找最后一个与key相等的小标,若不存在,则返回-1
int BinSearch(int a[], int n, int key) { int m, l = 0, r = n - 1;//闭区间[0, n - 1] while (l < r) { m = l + ((r + 1 - l) >> 1);//向上取整 if (a[m] <= key) l = m; else r = m - 1; } if (a[l] == key) return l; return -1; }
5、查找第一个大于key的下标,若不存在,则返回-1 ==> 同upper_bound(arr+1, arr+n+1, key)
int BinSearch(int a[], int n, int key) { int m, l = 0, r = n - 1;//闭区间[0, n - 1] while (l < r) { m = l + ((r - l) >> 1);//向下取整 if (a[m] <= key) l = m + 1; else r = m; } if (a[r] > key) return r; return -1; }
6、查找最后一个小于key的下标,若不存在,则返回-1
int BinSearch(int a[], int n, int key) { int m, l = 0, r = n - 1;//闭区间[0, n - 1] while (l < r) { m = l + ((r + 1 - l) >> 1);//向上取整 if (a[m] < key) l = m; else r = m - 1; } if (a[l] < key) return l; return -1; }
标签:大于 一个 upper lap one turn microsoft 种类 存在
原文地址:http://www.cnblogs.com/Rubbishes/p/7856400.html