7-1 二分查找 (20分)

利用二分查找找出所给出的数在数组中的下标

输入格式:
第一行输入n和m表示数组有n个数据,m表示要对m个数进行查找

输出格式:
所有输出在一行完成,行末没有多余空格和多余回车。

输入样例:

5 5
1 2 3 4 5
1 2 3 4 5

输出样例:

0 1 2 3 4

一开始无脑map,啊这,TEL。换scanf,printf,啊这,依旧TEL,那我就写个二分查找吧。算了,不写了,直接调用库函数。

C++ STL中的Binary search(二分查找)

#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    
    
	int n,m;
	scanf("%d %d",&n,&m);
	int a[n];
	for(int i = 0;i<n;i++){
    
    
		scanf("%d",&a[i]);
	}
	int num;
    scanf("%d",&num);
    int pos = lower_bound(a,a+n,num)-a;
    printf("%d",pos);
	for(int i = 1;i<m;i++){
    
    
		scanf("%d",&num);
		pos = lower_bound(a,a+n,num)-a;
		printf(" %d",pos);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45845039/article/details/110951733