1041 Be Unique (20 分)
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。
然后再遍历一编梅尔数组,如果有编号不为-1的梅尔,那么输出这个梅尔,否则在最后输出-1。
但是还有更加巧妙一点点的做法。
因为要求的是第一个,所以有一些信息就没有用了,比如说答案元素后面的元素是否重复等。
所以可以用一个队列存储梅尔-编号数据对,一个哈希表存储梅尔-编号键值对,然后遍历梅尔编号数组,如果遍历到的梅尔没有在哈希表出现过,那么将这个梅尔加入队列和哈希表中。否则将这个梅尔在哈希表中的编号设置为-1,同时开始维护队列,让队列队首的元素编号不为-1。
遍历结束后如果队列还有数据,那么这些数据的首部就是要求答案,否则就没有答案,输出None。
AC代码
#include <iostream>
#include <queue>
#include <map>
#include <vector>
#include <unordered_map>
using namespace std;
unordered_map<int, int> position;
queue<pair<int, int>> possible;
vector<int> nums;
int main() {
int N;
cin >> N;
nums.resize(N);
for (int i = 0; i < N; i++) {
scanf("%d", & nums[i]);
}
for (int i = 0; i < N; i++) {
if (!position.count(nums[i])) {
position[nums[i]] = i;
possible.emplace(nums[i], i);
}
else {
position[nums[i]] = -1;
while (!possible.empty() && position[possible.front().first] == -1) {
possible.pop();
}
}
}
if (possible.empty())cout << "None";
else {
cout << possible.front().first;
}
return 0;
}