【算法学习记录-散列】【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]. 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.
Input Specification:
Each input file contains one test case. Each case contains a line which begins with a positive integer N (≤) and then followed by N bets. The numbers are separated by a space.
Output Specification:
For each test case, print the winning number in a line. If there is no winner, print None instead.
Sample Input 1:
7 5 31 5 88 67 88 17
Sample Output 1:
31
Sample Input 2:
5 888 666 666 888 888
Sample Output 2:
None
思路:
0、《算法笔记》给出的参考答案是使用两个数组,作者使用的是二维数组,相比更繁杂
1、整体思路
建立arr[10000][2],其中第一列存放下标数值出现的次数,第二列存放下标数值出现的顺序(参考答案是用另外一个数字存放输入内容,从而得到顺序)
首先,for循环输入所有数据以及出现顺序,注意需要用if判断“顺序”属性是否是第一次输入
而后,for循环寻找只出现一次且是第一个被输入的数据
2、题解代码
1 #include<cstdio> 2 3 int main() { 4 5 int arr[10000][2]; 6 for (int i = 0; i < 10000; i++) { 7 arr[i][0] = 0; 8 arr[i][1] = 100010; 9 } 10 11 int n; 12 scanf("%d", &n); 13 for (int i = 0; i < n; i++) { 14 int num; 15 scanf("%d", &num); 16 arr[num][0]++; 17 if (arr[num][1] == 100010) { 18 arr[num][1] = i; 19 } 20 } 21 22 int k = 100010, win = 0;//为什么是100010?首先因为一共最多有100000个数据,然后这是用arr[i][1] < k的逻辑来寻找第一个出现的数据,所以不能赋值0 23 for (int i = 0; i < 10000; i++) { 24 if (arr[i][0] == 1 && arr[i][1] < k) { 25 win = i; 26 k = arr[i][1]; 27 } 28 } 29 30 if (win != 0) { 31 printf("%d", win); 32 } else { 33 printf("None"); 34 } 35 36 return 0; 37 }
浙公网安备 33010602011771号