lowerBound,可以用来顺便解决掉 binarySearch;
int lowerBound(long[] A, int n, long target) {
int l = 0, r = n;
while (l < r) {
final int m = l + ((r - l) >> 1);
if (A[m] < target) {
l = m + 1;
} else {
r = m;
}
}
return l;
}
boolean binarySearch(long[] A, int n, long target) {
int l = lowerBound(A, n, target);
return l < n && A[l] == target;
}
写一个函数 upperBound 寻找数组中给定元素的上界
int upperBound(long[] A, int n, long target) {
int l = 0, r = n;
while (l < r) {
final int m = l + ((r - l) >> 1);
if (A[m] <= target) {
l = m + 1;
} else {
r = m;
}
}
return l;
}