Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
有一个数据字典,里面存有n个数字(n<=100000),小明现在接到一个任务,这项任务看起来非常简单——给定m个数字,分别查询这m个数字是否出现在字典之中;但是考虑到数据量的问题,小明找到了善于编程的你,希望你可以帮他解决这个问题。
Input
输入数据只有一组!
第一行包含两个整数n m,分别代表字典中数字的个数和要查询的数字的个数。
接着n行代表字典中的n个数字。
最后m表示要查询的数字。
Output
如果某个数字存在,则输出YES,否则输出NO
Sample Input
5 3
1
2
3
4
5
5
4
10
Sample Output
YES
YES
NO
Hint
Source
赵利强
注意:超时了很多次,最开始的代码非常粗暴,开了一个100000的数组,代表的是每一个输入的数字,凡是出现了便在这个数组中对其值加1,定义一个flag变量,凡是出现了这个数便将flag设为1,设为1,再输出YES即可。
贴上超时的代码:
#include <iostream>
using namespace std;
void find_n(int a[],int n,int key)
{
int flag[100000]={0};
for(int i=0;i<n;i++)
{
flag[a[i]]=1;
}
if(flag[key]==1)
{
cout<<"YES"<<endl;
}
else if(flag[key]==0)
{
cout<<"NO"<<endl;
}
}
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
int a[100000];
int n,m;
int key=0;
cin>>n>>m;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int j=0;j<m;j++)
{
cin>>key;
find_n(a,n,key);
}
return 0;
}
能过的代码:
#include <iostream>
using namespace std;
int flag[100000]={0};
void find_n(int a[],int n,int key)
{
if(flag[key]==1)
{
cout<<"YES"<<endl;
}
else if(flag[key]==0)
{
cout<<"NO"<<endl;
}
}
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
int a[100000];
int n,m;
int key=0;
cin>>n>>m;
for(int i=0;i<n;i++)
{
cin>>a[i];
flag[a[i]]=1;
}
for(int j=0;j<m;j++)
{
cin>>key;
find_n(a,n,key);
}
return 0;
}
相当于直接减少一次遍历吧