查找练习 hash——出现过的数字
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
赵利强
解题思路:建立一个数组,数组元素的下标就是这个数字本身,如果这个数字x出现过,就把a【x】的值为非0(我是出现过则+1),有点类似于桶式排序。
AC代码:
#include <iostream>
#include <queue>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
using namespace std;
int dir[100005];
int main()
{
int n, m;
scanf("%d %d", &n, &m);
memset(dir,0,sizeof(dir));
while(n--)
{
int a;
scanf("%d", &a);
dir[a]++;
}
//printf("\n");
while(m--)
{
int b;
scanf("%d", &b);
if(dir[b] != 0)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}