Codeup——585 | 问题 C: 查找

题目描述

输入数组长度 n
输入数组 a[1…n]
输入查找个数m
输入查找数字b[1…m]
输出 YES or NO 查找有则YES 否则NO 。

输入

输入有多组数据。
每组输入n,然后输入n个整数,再输入m,然后再输入m个整数(1<=m<=n<=100)。

输出

如果在n个数组中输出YES否则输出NO。

样例输入

6
3 2 5 4 7 8
2
3 6

样例输出

YES
NO

思路:二分查找和简单查找都可以。如果要用二分查找的话记得要排序。

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

bool binarySearch(int a[],int left,int right,int x){
	int mid;
	while(left<=right){
		mid=left+(right-left)/2;
		if(a[mid]==x) return true;
		else if(a[mid]>x) right=mid-1;
		else left=mid+1;
	}
	return false;
}

int main()
{
	int i,n,m,left,right;
	int a[100],b[100];
	while(scanf("%d",&n)!=EOF){
		for(i=0;i<n;i++)
			cin >>a[i];
		sort(a,a+n);
		cin >>m;
		for(i=0;i<m;i++){
			cin >>b[i];
			if(binarySearch(a,0,n-1,b[i]))
				cout <<"YES"<<endl;
			else 
				cout <<"NO"<<endl;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44888152/article/details/106818558