二分查找,非常适合在有序数组中进行查找,时间复杂度为 O ( l o g n ) O(logn) O(logn)。
当有序数组中有多个重复元素时,二分查找就出现了 lower_bound 和 upper_bound,这两个函数都可以直接调用。注意这两个函数返回值都是迭代器类型。
// array: 1 2 2 2 2 4 5
int low = lower_bound(arr.begin(), arr.end(), 2) - arr.begin(); // 1
int high = upper_bound(arr.begin(), arr.end(), 2) - arr.begin(); // 4
自己实现 lower_bound 和 upper_bound
int mybin_lower(vector<int>& arr, int targ) {
int len = arr.size();
int low = 0, high = len - 1;
int ans = 0;
while(low <= high) {
int mid = (low + high) >> 1;
if (arr[mid] >= targ) {
high = mid - 1;
ans = mid;
} else {
low = mid + 1;
}
}
return ans;
}
int mybin_higher(vector<int>& arr, int targ) {
int len = arr.size();
int low = 0, high = len - 1;
int ans = 0;
while(low <= high) {
int mid = (low + high) >> 1;
if (arr[mid] > targ) {
high = mid - 1;
} else {
low = mid + 1;
ans = mid;
}
}
return ans;
}
int main()
{
vector<int> nums{1, 1, 2, 2, 2, 2, 6, 7, 8};
int lower = mybin_lower(nums, 2);
int higher = mybin_higher(nums, 2);
cout << lower << " " << higher << endl;
}