题解 | #查找#
二分查找注意事项: 1.while(low<=high) =去掉所有用例都是NO 2.每次high = mid -1,low = mid +1 +-1不能忘,否则结果超时
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
string binarySearch(int test[],int n,int x){
int low = 0;int high = n-1;
while(low<=high){
int mid = (low+high)/2;
if(test[mid] == x) return "YES";
else if(test[mid]>x){high = mid-1;}
else if(test[mid]<x){low = mid+1;}
}
return "NO";
}
int main(){
int n;
while(cin>>n){
int num[n];
for(int i =0;i<n;i++){
cin>>num[i];
}
int k = 0;
cin>>k;
int item;
sort(num,num+n);
for(int i =0;i<k;i++){
cin>>item;
cout<<binarySearch(num,n,item)<<"\n";
}
}
}