【发布时间】:2011-09-27 02:14:15
【问题描述】:
在一般的二分搜索中,我们正在寻找出现在数组中的值。然而,有时我们需要找到大于或小于目标的第一个元素。
这是我丑陋的、不完整的解决方案:
// Assume all elements are positive, i.e., greater than zero
int bs (int[] a, int t) {
int s = 0, e = a.length;
int firstlarge = 1 << 30;
int firstlargeindex = -1;
while (s < e) {
int m = (s + e) / 2;
if (a[m] > t) {
// how can I know a[m] is the first larger than
if(a[m] < firstlarge) {
firstlarge = a[m];
firstlargeindex = m;
}
e = m - 1;
} else if (a[m] < /* something */) {
// go to the right part
// how can i know is the first less than
}
}
}
对于这类问题有更优雅的解决方案吗?
【问题讨论】:
-
数组排序了吗?如果是则二分查找,如果不是则线性查找...
-
它是一个排序数组,因此我们可以进行二进制搜索。在上面的代码中,我使用比较来查找数组中的第一个更大或更小的元素
-
为什么不使用upper_bound c++ STL
标签: arrays algorithm binary-search