先看一个问题:要求先输入数目 n , 再输入 n 个数(取值范围 0 到 100),n = 0 时程序结束,再输入一个值 a, 输出 n 个数中与 a 相同的数字的个数。
面对这样的问题,很容易想到的是将输入的 n 个数先存储起来,然后 将输入的 n 与上述的 n 个数进行比较,cnt++ 的方式最终输出胡个数,这里介绍的是 hash 的方法,即在输入 n 个数的同时,就将它们对应的个数进行存储,Hash[x]存储的就是 x 的个数,最终只要输出输入的 a 的Hash[a] 即可。
代码为:
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<vector>
#include<string.h>
using namespace std;
int main()
{
int n;
//当 n 为0时程序结束,这是程序的条件
while (scanf("%d", &n) != EOF && n != 0)
{
int Hash[101] = { 0 };
for (int i = 0; i < n; i++)
{
int x;
scanf("%d",&x);
Hash[x]++;
}
int a;
scanf("%d",&a);
printf("%d",Hash[a]);
}
return 0;
}
运行结果为:
3
90 80 60
60
1
4
90 80 60 60
60
2
4
90 80 60 90
60
1
再看第二个例子:
题目描述:
给你 n 个整数,请按从大到小的顺序输出其中前 m 大的数。
输入:
每组测试数据有两行,第一行有两个数 n,m(0<n,m<1000000),第二行包含 n个各不相同,且都处于区间[-500000,500000]的整数。
输出:
对每组测试数据按从大到小的顺序输出前 m 大的数。
样例输入:
53
3 -35 92 213 -644
样例输出:
213 92 3
注意的是输入的 n 个数各不相同,要注意的是这里最好不能用 sort, 因为 n 最大可能取到1000000,快排的时间复杂度为O(nlogn) , 会超出一秒的时间限制,这是可以考虑 hash 这种方法,即以空间换时间,因为存储值以及遍历一遍的时间复杂度最多为O(1),这样可以大大提高程序的效率。
代码为:
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<vector>
#include<string.h>
using namespace std;
//define后面不能加;会报错!!!这也是前面程序出现错误的原因
#define OFFSET 500000
//当分配较大数组时就在函数外定义,共有100001个值
int Hash[1000001];
int main()
{
int n, m;
while (scanf("%d%d", &n, &m) != EOF)
{
//全部初始化为0,一会试试{0}的操作
for (int i = -500000; i <= 500000; i++)
Hash[i + OFFSET] = 0;
for (int i = 0; i < n; i++)
{
int x;
scanf("%d",&x);
//因为题目要求输入的 n 个数不能重复,所以用 0 和 1 就能存储下来
Hash[x + OFFSET] = 1;
}
int cnt = 0;
for (int i = 500000; i >= -500000, cnt != m; i--)
{
if (Hash[i + OFFSET] != 0)
{
printf("%d", i);
cnt++;
//当已经输出 m 个值时将会打印一个换行符
//没有时则在每个新打印的值后增加一个空格,而不是再%d后面加上一个空格
//在%d后加空格,最后一个数打印时可能会因为打印一个空格和一个换行出现错误
//这一点以后在继续观察
if (cnt == m)
{
printf("\n");
break;
}
else
printf(" ");
}
}
}
return 0;
}
运行结果:
6 2
100 300 400 10 20 301
400 301
5 3
3 -35 92 213 -644
213 92 3