题目描述:
读入N名学生的成绩,将获得某一给定分数的学生人数输出。
输入:
测试输入包含若干测试用例,每个测试用例的格式为
第1行:N
第2行:N名学生的成绩,相邻两数字用一个空格间隔。
第3行:给定分数当读到N=0时输入结束。其中N不超过1000,成绩分数为(包含)0到100之间的一个整数。
输出:
对每个测试用例,将获得给定分数的学生人数输出。
样例输入:
3
80 60 90
60
2
85 66
0
5
60 75 90 55 75
75
0
样例输出:
1
0
2
最容易想到的解法,AC代码:
#include <stdio.h>
#include <stdlib.h>
int buf[1000];
int main()
{
int count=0;
int n;
int temp;
while(scanf("%d",&n)!=EOF){
if(n==0){
break;
}else{
for(int i=0;i<n;i++){
scanf("%d",&buf[i]);
}
scanf("%d",&temp);
for(int i=0;i<n;i++){
if(buf[i]==temp)
count++;
}
printf("%d",count);
printf("\n");
}
}
return 0;
}
/*
80 60 90
60
2
85 66
0
5
60 75 90 55 75
75
0
*/
利用hash方法来解决,将输入的数据直接作为Hash数组的下标,累加统计其重复次数,在查询某个分数的次数时,只需统计其出现的数组元素Hash[x]即可。
AC代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF && n!=0){ //输入判断增加对n是否为进行判断
char Hash[101] = {0}; //建立一个初始为0的Hash数组来记录各种分数出现的次数
//input
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
Hash[x]++; //统计分数出现的次数
}
int x;
scanf("%d",&x);
//得到需要查询的分数后,只需简单的查询我们统计的数量即可
printf("%d\n",Hash[x]);
}
return 0;
}
/*
3
80 60 90
60
2
85 66
0
5
60 75 90 55 75
75
0
*/
688

被折叠的 条评论
为什么被折叠?



