PAT-A 1041 Be Unique (20 分)

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,10​4​​]. 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 (≤10​5​​) and then followed by Nbets. 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

思路:使用map<int, int>保存竞猜过的数字和被竞猜的次数,遍历竞猜的数字,如果发现当前数字只被竞猜过一次,立即打印胜者,程序结束,如果所有的数字被竞猜的次数都不止一次,打印None

#include <bits/stdc++.h>
#define maxn 100005

using namespace std;

int bets[maxn];
int main()
{
    int n;
    scanf("%d", &n);

    map<int, int> m;//号码->数量
    for(int i = 0; i < n; i++)
    {   //统计每个竞猜过的号码及其出现的次数
        scanf("%d", bets + i);
        if(m.find(bets[i]) == m.end())
            m[bets[i]] = 1;
        else
            m[bets[i]]++;
    }

    int win = 0;//竞猜从1开始
    for(int i = 0; i < n; i++)
    {   //如果发现一个只竞猜过一次的数字,获胜
        if(m[bets[i]] == 1)
        {
            win = bets[i];
            break;
        }
    }

    if(win)//有人胜出
        printf("%d", win);
    else
        printf("None");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38127801/article/details/86515689