二分查找
# include <iostream>
# include <algorithm>
# include <cmath>
# include <string>
# include <cstring>
using namespace std;
int main(){
int m , n , x;
cin >> n >> m ;
int a[1000];
for (int i = 0 ; i < n ; i++)
cin >> a[i];
while (m -- ){
cin >> x;
int left = 0 ,right = n ;
while (left < right ){
int mid = (left + right ) / 2;
if (a[mid] >= x)
right = mid ;
else left = mid + 1;
}
if (a[left]!=x){
cout << " no "<< endl;
continue;
}
cout << left << endl;
}
return 0 ;
}
lower_bound 和 upper_bound 在algorithm 头文件中 利用 二分查找 对有序数组进行查找
lower_bound 会返回数组中大于等于 被查数 的 地址 , 查找坐标即 -a
upper_bound 返回数组 小于 被查数 的地址 ,查找坐标 -a
# include <iostream>
# include <algorithm>
# include <cmath>
# include <string>
# include <cstring>
using namespace std;
const int N = 2000000;
int main(){
int m , n , x;
cin >> n >> m ;
int a[1000];
int b[1000];
for (int i = 0 ; i < n ; i++)
cin >> a[i];
int cnt = 0 ;
sort (a, a+n );
while ( m -- ){
cin >> x ;
int t1 = upper_bound(a,a+n,x) - a ;//找出 数组中 第一个小于被查数x的坐标
int t2 = lower_bound(a,a+n,x) - a; // 找出数组中第一个大于或等于 被查数的坐标
cout << a[t1] << endl ;
cout << a[t2] << endl ;
}
return 0 ;
}