码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2018-11-24 21:08:29      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:eof   app   int   lis   hit   cto   pac   cstring   pause   

解法一:

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;
}

 

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

标签:eof   app   int   lis   hit   cto   pac   cstring   pause   

原文地址:https://www.cnblogs.com/ruoh3kou/p/10013174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!