zoukankan      html  css  js  c++  java
  • [小米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;
    }
  • 相关阅读:
    four day (linux基础学习1)
    three day(网络基础)
    two day(操作系统)
    Oldboy One day(计算机基础)
    mybatis调用存储过程
    调用jiathis分享接口
    汉字转换拼音工具类
    Ajax前后台交互 返回普通格式和JSON格式
    Bootstrap与EasyUI入门
    MD5,sha1加密工具类
  • 原文地址:https://www.cnblogs.com/ruoh3kou/p/10013174.html
Copyright © 2011-2022 走看看