研0 冲刺算法竞赛 day29 P2249 【深基13.例1】查找

P2249 【深基13.例1】查找 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

思路:

①二分查找

②stl函数:lower_bound(a.begin(),a.end(),x) 返回第一个大于等于 x的数的地址

代码:

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

int n, m;
int a[1000005];

//int find(int x) //二分查找 
//{
//	int l = 1, r = n;
//	while (l < r)
//	{
//		int mid = l + (r - l) / 2;
//		if (a[mid] >= x) r = mid;
//		else l = mid + 1;
//	}
//
//	if (a[l] == x) return l; //找都了就输出他的位置 
//	else return -1; // 没找到输出-1 
//}
//
int main()
{
	cin >> n >> m;

	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];//待查询
	}
	while (m--)
	{
		int x;
		cin >> x;
		int ans = lower_bound(a + 1, a + n + 1, x) - a;//可换二分查找
		if (x == a[ans])//找到了
		{
			cout << ans << " ";
		}
		else
			cout << -1 << " ";
	}
	return 0;
}

总结:记二分查找代码和lower_bound用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值