[小米OJ] 2. 找出单独出现的数字

解法一:

map

 1.45 ms

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;

int main()
{
    int temp;
    map<int, int> mapping;
    while (scanf("%d", &temp) != EOF)
    {
        mapping[temp]++;
    }
    for (map<int, int>::iterator it = mapping.begin(); it != mapping.end(); it++)
    {
        if (it->second == 1)
        {
            printf("%d", it->first);
        }
    }
    system("pause");
    return 0;
}

解法二:

因为题目提出“其中仅有一个数字出现过一次,其他数字均出现过两次”,即可以利用异或计算

一个数字异或它自己结果为0,异或0结果为它自己即a^a=0,a^0=a,且异或满足a^b^c=a^(b^c)。

因此我们可以设置一个ret异或每个元素,最后相同的都抵消为0,那个唯一的数字异或0为它自己即为答案。

1.97 ms

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;

int main()
{
    int temp;
    int arr[21];
    int i = 0;
    while (scanf("%d", &temp) != EOF)
    {
        arr[i] = temp;
        i++;
    }
    int ret = 0;
    for (int j = 0; j < i; j++)
    {
        ret ^= arr[j];
    }
    printf("%d",ret);
    system("pause");
    return 0;
}

 

posted @ 2018-11-24 19:38  Ruohua3kou  阅读(391)  评论(1编辑  收藏  举报