二分查找,没什么好说的。关键在于排成有序数组。然而C++调用sort就可以了。
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
bool judge(int* A, int n ,int t){
int head = 0;
int tail=n-1;
while(head <= tail){
int mid=(head+tail)/2;
if(A[mid]==t){
return true;
}else if(A[mid] < t ){
head=mid+1;
}else{
tail=mid-1;
}
}
return false;
}
int main(){
int n ;
while(cin >> n){
int* A=(int*)malloc(sizeof(int )*n);
for(int i = 0 ; i < n; i++){
cin >> A[i];
}
sort(A,&A[n]);
int m ;
cin >> m ;
for( int i = 0 ; i < m ; i++ ){
int t;
cin >> t;
if(judge(A,n,t)) {
printf("YES\n");
}else{
printf("NO\n");
}
}
}
return 0;
}
结果如下:
标签:int,KY199,cin,C++,查找,printf,include From: https://www.cnblogs.com/llllmz/p/17962412