二分
// Return the position of an element in sorted array "A" of
// size "n" with value "K". If "K" is not in "A", return
// the value "n".
int binary(int A[], int n, int K) {
int l = -1;
int r = n; // l and r are beyond array bounds
while (l+1 != r) { // Stop when l and r meet
int i = (l+r)/2; // Check middle of remaining subarray
if (K < A[i]) r = i; // In left half
if (K == A[i]) return i; // Found it
if (K > A[i]) l = i; // In right half
}
return n; // Search value not in A
}
lower_bound 和 upper_bound
lower_bound 返回数组中第一个不小于目标值的元素的iterator,(第一个>=target的数)
upper_bound 返回数组中第一个大于目标值的元素的iterator, (第一个>target的数)
int my_low_boundint(vector<int>& nums, int target) {
// 找到比n大于或等于的第一个元素
int l = 0, r = nums.size(), mid; // r = n的设计是为了
while (l < r) {
mid = l + ((r - l) >> 1); // 防止溢出的设计, 移位更快
if (nums[mid] < target) {
// 小于的时候向右移动,直到移动到大于等于target就不变了
l = mid + 1;
} else {
// 直至移动到和l相同的地方
r = mid;
}
}
return l;
}
int my_up_bound(vector<int> index , int n){
// 找到比n大的第一个元素
int l = 0,r = index.size(),mid;
while(l<r){
mid = l + ((r - l) >> 1); // 防止溢出的设计, 移位更快
if(index[mid] <= n) l = mid +1; // 小于的时候向右移动,直到移动到大于target就不变了
else r = mid; // 比n大就一直向左边移动
}
return l;
}
c++ STL 版使用
c++ STL
中upper_bound
和lower_bound
头文件 #include<algorithm>
函数功能:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。
函数功能:函数upper_bound在first和last中的前闭后开区间进行二分查找,返回大于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int array[5] = {1 , 2 , 2 , 3 , 5 };
int t1 = upper_bound( array , array+5 , 2 )-array;
//t1 = 3 ; array[t1] = 3;
int t2 = lower_bound( array , array+5 , 2 )-array;
//t2 = 1 ; array[t2] = 2;
return 0;
}