也是好久之前的了,拿出来落落灰
二分
题目1:
一道题通天下,如果能做出这个,基本上二分基础没什么问题了
题解:
易错提醒:
题目描述2
输入n个不大于1e9的单调不减的非负整数然后有m次询问,对于每次询问输出该数字在数列中第一次出现时的序号。如果没有找到输出-1。
输入格式
第一行 2 个整数 n 和 m,表示数字个数和询问次数。 1
第二行 n 个整数,表示这些待查询的数字。
第三行 m 个整数,表示询问这些数字的编号,从 1 开始编号。
输出格式
m个整数表示答案
样例
输入数据 1
11 3 1 3 3 3 5 7 9 11 13 15 15 1 3 6
Copy
输出数据 1
1 2 -1
Copy
Limitation
2s, 1024KiB for each test case.
#include<bits/stdc++.h>
using namespace std;
const int N =1e7+7;
int a[N];
int search(int *a,int key,int j){
int l=1,r=j-1;
while(l<=r){
int mid=(l+r)>>1;
if(a[mid]==key) r=mid-1;
else if(a[mid]<key) l=mid+1;
else if(a[mid]>key) r=mid-1;
}
if(l>=j||a[l]!=key) return -1;//区别在这,不要多写=,不然数据不会过
else return l;
}
int main(){
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
while(m--){
int k;
cin>>k;
int f=search(a,k,n);
cout<<f<<" ";
}
return 0;
}
易错提醒