B2093 查找特定的值 题解
原题传送门
对于这道题,我们固然可以一个一个去查找(即“顺序查找法”),但我们还可以用更优的方法——哨兵查找法。
先看一下代码。
#include<iostream>
using namespace std;
int n,a[20000],x,p;
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
cin>>x;
a[n]=x;
while(a[p]!=x)p++;
if(p==n)cout<<"-1";
else cout<<p;
return 0;
}
“哨兵”指的就是 while循环中确认
换句话说,我们把原来的
while(p<n){
if(a[p]==x){
cout<<p;
return 0;
}
p++;
}
cout<<"-1";
return 0;
写成了
while(a[p]!=x)p++;
if(p==n)cout<<"-1";
else cout<<p;
return 0;
不但使代码看上去更加简洁,还省去判断
参考文献