二分搜索
题目描述
给定n个元素,使用二分法从中查找特地元素x。
输入
包含T组数据。先给定一个T。每组数据第一行是n,第二行是n个数。第三行为要查找的数x
T<2000,n<100000
输出
先输出排序后的数组。如果找到x,则输出x的位置;如果没找到,输出“-1”。
样例输入
1
11
60 17 39 15 8 34 30 45 5 52 25
17
样例输出
5 8 15 17 25 30 34 39 45 52 60
4
提示
#include<iostream> #include<algorithm> using namespace std; int main() { int T; cin>>T; while(T--) { int n; cin>>n; int a[100005]; for(int i=1;i<=n;i++) { cin>>a[i]; } sort(a+1,a+n+1); int x; cin>>x; int l=1,r=n; int mid; while(l<=r) { mid=(l+r)/2; if(a[mid]<x) { l=mid+1; } else if(a[mid]>x){ r=mid-1; } else{ l=mid; break; } } for(int i=1;i<=n;i++) { if(i!=n) cout<<a[i]<<" "; else cout<<a[i]<<endl; } if(a[l]==x) cout<<l<<endl; else cout<<-1<<endl; } return 0; }
或者
#include<iostream> #include<algorithm> using namespace std; int main() { int T; cin>>T; while(T--) { int n; cin>>n; int a[100005]; for(int i=1;i<=n;i++) { cin>>a[i]; } sort(a+1,a+n+1); int x; cin>>x; int l=1,r=n; int mid; while(l<=r) { mid=(l+r)/2; if(a[mid]<x) { l=mid+1; } else if(a[mid]>x){ r=mid-1; } else{ r=mid; break; } } for(int i=1;i<=n;i++) { if(i!=n) cout<<a[i]<<" "; else cout<<a[i]<<endl; } if(a[r]==x) cout<<r<<endl; else cout<<-1<<endl; } return 0; }
http历史
http基础
那些年我踩过的electron+react的坑!!!
【Error】System limit for number of file watchers reached
zsh: corrupt history file /home/floodlight/.zsh_history
electron中持久化保存数据的解决方案electron-store
坑:pytest 运行报错unknown hook 'pytest_namespace' in plugin <module 'allure.pytest_plugin'
坑:找到LoadRunner中Recording Options和 Run Time Settings配置选项确实的原因
Loadrunner基本概念解析<一>