PAT 1041.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.

Input Specification:

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.

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

我的解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>

//解题思路:
//1.将元素存入一个vector nums
//2.用一个vector count统计每个元素出现的次数
//3.遍历nums,查看每个元素在count中的值,即其
//出现的次数,若为1,则说明是第一个unique number

using namespace std;

int main()
{
int n, winner = 0;
vector<int> nums; //保存元素,主要目的是保存元素出现的次序
vector<int> count(10010, 0); //下标表示元素,值表示该元素出现次数

cin >> n;
for (int i = 0; i < n; ++i) {
int x;

cin >> x;
if (x >= 1 && x <= 10000) {
nums.push_back(x);
++count[x];
}
}

for (const auto x : nums) {
if (count[x] == 1) {
winner = x;
break;
}
}

if (winner) {
cout << winner << endl;
}
else {
cout << "None" << endl;
}

return 0;
}
Author: sphc
Link: https://jkuvw.xyz/archives/82995bf6/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
微信打赏
支付宝打赏