算法笔记练习 4.2 散列 问题 C: 【PAT A1041】Be Unique
题目
题目描述
Being unique is so important to people on Mars that even their lottery is designed in a unique way. The rule of winning is simple: one bets on a number chosen from [1, 104]. The first one who bets on a unique number wins. For example, if there are 7 people betting on 5 31 5 88 67 88 17, then the second one who bets on 31 wins.
输入
Each input file contains one test case. Each case contains a line which begins with a positive integer N (<=105) and then followed by N bets. The numbers are separated by a space.
输出
For each test case, print the winning number in a line. If there is no winner, print “None” instead.
样例输入
7 5 31 5 88 67 88 17
5 888 666 666 888 888
样例输出
31
None
思路
- 用 inputs 接收所有输入,同时用 cnt 数组统计所有数字的出现次数(cnt[i] 表示数字 i 出现的次数)
- 遍历 inputs,在 cnt 中检查每个数的出现次数,若存在出现次数为 1 的数,立即输出,若没有找到,输出 None
代码
#include <stdio.h>
#define MAX 100010
int main(){
int N, i;
while (scanf("%d", &N) != EOF){
int inputs[N];
int cnt[MAX] = {0};
// 接收所有数字,并用 cnt 统计出现次数
for (i = 0; i < N; ++i){
scanf("%d", &inputs[i]);
++cnt[inputs[i]];
}
// 遍历 inputs,若存在出现次数为 1 的数,立即输出
for (i = 0; i < N; ++i){
if (cnt[inputs[i]] == 1){
printf("%d\n", inputs[i]);
break;
}
}
// 没找到
if (i == N)
printf("None\n");
}
return 0;
}