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;
    }
  • 相关阅读:
    Leetcode#117 Populating Next Right Pointers in Each Node II
    Leetcode#123 Best Time to Buy and Sell Stock III
    获取文件大小的方法
    内存映射
    git patch
    git cherry-pick
    关于extern的说明
    Linux如何查看与/dev/input目录下的event对应的设备
    如何在Linux下统计高速网络中的流量
    [: ==: unary operator expected 解决方法
  • 原文地址:https://www.cnblogs.com/ruoh3kou/p/10013174.html
Copyright © 2011-2022 走看看