当前位置:网站首页>上课笔记(5)(1)——#593. 二分查找(binary)
上课笔记(5)(1)——#593. 二分查找(binary)
2022-07-28 01:03:00 【xyc20120615】
Description
给出有 n 个元素的由小到大的序列,请你编程找出某元素第一次出现的位置。(n≤10^6)
Format
Input
第一行:一个整数,表示由小到大序列元素个数;
下面 n 行,每行一个整数;
最后一行一个整数 x,表示待查找的元素;
Output
如果 x 在序列中,则输出 x 第一次出现的位置,否则输出 -1。
Samples
输入数据 1
5
3
5
6
6
7
6
输出数据 1
3
Limitation
1s, 1024KiB for each test case.
方法一:
看这名字就知道要用二分,但我不信邪,试了试暴力搜,竟然AC了!,不得不吐槽一下,那个OJ的数据是真的水。
程序:
#include<bits/stdc++.h>//不建议使用本程序,很有可能爆零
using namespace std;
int n,x,a[1000010];
int main(){
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
cin>>x;
for(int i=1;i<=n;i++)
if(a[i]==x){
cout<<i;
return 0;
}
coutt<<-1;
return 0;
}方法二:
就是正常的二分查找,大致思路就是开两个变量设定范围然后根据变的之间值不断缩小范围纸质找到,注意在数组是有序的情况下才能进行二分,要么就先排序。
程序:
#include<bits/stdc++.h>
using namespace std;
int n,x,a[1000010];
int main(){
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
cin>>x;
int l=1,r=n;
while(l<=r){
int mid=(l+r)/2;
if(a[mid]<x)
l=mid+1;
else
r=mid-1;
}
if(a[l]!=x){
cout<<-1;
return 0;
}
cout<<l;
return 0;
}PS:方法一请谨慎使用!
边栏推荐
- C # using ABP warehouse to access the database error record set
- Likeshop takeout ordering system [100% open source, no encryption]
- 小程序毕设作品之微信校园浴室预约小程序毕业设计成品(1)开发概要
- 【Star项目】小帽飞机大战(五)
- Promise from getting started to mastering (Chapter 3: customize (handwriting) promise)
- go 学习02 基础知识
- 小程序毕设作品之微信校园维修报修小程序毕业设计成品(4)开题报告
- Flex development web page instance web side
- Common video resolution
- [database data recovery] data recovery case of insufficient disk space of SQL Server database
猜你喜欢

重要安排-DX12引擎开发课程后续直播将在B站进行

Codeforces Round #810 (Div. 2)A~C题解

Two ways for wechat applet to realize dynamic horizontal step bar

QGIS制图:矢量数据制图流程及导出

Sample imbalance - entry 0

Appium 点击操作梳理

uniapp 总结篇 (小程序)
![[database data recovery] data recovery case of insufficient disk space of SQL Server database](/img/0e/908db40e1e8b7dd62e12558c1c6dc4.png)
[database data recovery] data recovery case of insufficient disk space of SQL Server database

Flex development web page instance web side

Common problem types and methods of mathematical univariate differential proof problems in postgraduate entrance examination
随机推荐
都在说DevOps,你真正了解它吗?
数字赋能 创新未来:海丝埃睿迪亮相第五届数字中国建设峰会
MySQL create stored procedure ------ [hy000][1418] this function has none of deterministic, no SQL
mongodb/mongoTemplate.upsert批量插入更新数据的实现
Likeshop takeout ordering system [100% open source, no encryption]
借助Elephant&nbsp;Swap打造的ePLATO,背后的高溢价解析
Codeforces Round #810 (Div. 2)A~C题解
【ROS进阶篇】第十讲 基于Gazebo的URDF集成仿真流程及实例
Software test interview question: please introduce the meaning of various test types in detail?
MySQL高可用和主从同步
数据输出-图片注释、标注
In it, there is a million talent gap, and the salary rises, but it is not capped
重要安排-DX12引擎开发课程后续直播将在B站进行
[深入研究4G/5G/6G专题-42]: URLLC-14-《3GPP URLLC相关协议、规范、技术原理深度解读》-8-低延时技术-2-基于slot的调度与Slot内灵活的上下行符号配比
一种比读写锁更快的锁,还不赶紧认识一下
go 学习02 基础知识
Go learn 02 basic knowledge
Data output - image annotation and annotation
IT这个岗位,人才缺口百万,薪资水涨船高,上不封顶
Day6 函数和模块的使用