题解 | #查找#
查找
http://www.nowcoder.com/practice/d93db01c2ee44e8a9237d63842aca8aa
//二分查找需要先使排列元素有序 #include #include #include
using namespace std;
const int Maximum = 100; int array[Maximum];
bool Binary_Search(int n,int target){ int left = 0; int right = n-1; while(left <= right){ int middle = (left+right)/2; if(target < array[middle]){ right = middle-1; } else if(target > array[middle]){ left = middle+1; } else{ return true; } } return false; }
int main(){ int n,m; while(cin>>n){ for(int i=0; i<n; i++){ cin>>array[i]; } sort(array,array+n); cin>>m; for(int j=0; j<m; j++){ int temp; cin>>temp; if(Binary_Search(n,temp)){ cout<<"YES"<<endl; } else{ cout<<"NO"<<endl; } } } return 0; }