1010: 折半查找的实现

解法:

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;
void solve() {
	int n;
	cin >> n;
	vector<int> vec(n);
	for (int& x : vec) cin >> x;
	int x;
	cin >> x;
	int l = 0, r = n-1, cnt = 0;
	while (l <= r) {
		cnt++;
		int mid = l + (r - l) / 2;
		if (vec[mid] > x) 
			r = mid - 1;
		else if (vec[mid] < x)
			l = mid + 1;
		else {
			cout << mid << endl;
			cout << cnt;
			return;
		}
	}
	cout << -1 << endl;
	cout << cnt;
}
int main() {
	solve();
	return 0;
}
相关推荐
微笑星河q7 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
HaiXCoder10 小时前
C++ 表达式怎么读:从一行代码到类型、值类别和生命周期
c++
武子康10 小时前
H3-World 扩展跳跃与开门:新动作怎样进入训练数据?
大数据·人工智能·算法
卡尔曼的BD SLAMer10 小时前
北斗导航 |GNSS ION论文集汇总1997到2022(链接在文末)
算法·北斗导航
时间的拾荒人10 小时前
Redis Cluster 集群详解:分片算法、搭建、故障处理与扩容实战
数据库·redis·算法·集群
老师我太想进步了202613 小时前
【数据结构-8】栈的实现
c语言·数据结构·算法
kyle~14 小时前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
geats人山人海14 小时前
现代c++4.1
java·开发语言·c++
Pniubi15 小时前
贪心算法入门
算法·贪心算法
MobotStone15 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法