版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/89045673
Problem Description:
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:
代码语言:javascript复制7 5 31 5 88 67 88 17
Sample Output 1:
代码语言:javascript复制31
Sample Input 2:
代码语言:javascript复制5 888 666 666 888 888
Sample Output 2:
代码语言:javascript复制None
解题思路:
题目简单来说就是一句话:“输出第一个只出现一次的数”,这肯定直接无脑map啊。然而在我对map进行无脑for-each来输出第一个只出现一次的数的时候我发现我错了,C 的map会自动根据key值来进行升序排列,它并不是像Java的LinkedHashMap一样能够按照输入的顺序来排列。这就很尴尬了,那只能够对输入的序列来进行遍历,然后输出第一个只出现一次的数。
AC代码:
代码语言:javascript复制#include <bits/stdc .h>
using namespace std;
int main()
{
int N;
cin >> N;
int a[N];
map<int,int> m;
for(int i = 0; i < N; i )
{
cin >> a[i];
m[a[i]] ;
}
bool flag = true;
//不能这样直接无脑for-each,因为C 的map会自动根据key值来升序排列,它不像Java的LinkedHashMap一样是能按照输入的顺序排列的
// for(auto it : m)
// {
// if(it.second == 1)
// {
// cout << it.first << endl;
// flag = false;
// break;
// }
// }
for(int i = 0; i < N; i )
{
if(m[a[i]] == 1) //输出第一个只出现过一次的数
{
cout << a[i] << endl;
flag = false;
break;
}
}
if(flag)
{
cout << "None" << endl;
}
return 0;
}