Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

It is not a big deal at the first sight: https://oj.leetcode.com/problems/single-number/

And my AC code is straightforward:

#include <unordered_set> 
using namespace std;

typedef unordered_set<int> Myset;

class Solution {
public:
    int singleNumber(int A[], int n) {
        
        Myset set;
        for (int i = 0; i < n; i++)
        {
            int n = A[i];
            if (set.find(n) == set.end())    set.insert(n);
            else                            set.erase(n);
        }        
        return *set.begin();
    }
};

But I was completely shocked by the optimal solution: 

class Solution {
public:
    int singleNumber(int A[], int n) {
        int x = 0;
        for (int i = 0; i < n; i ++)
            x ^= A[i];
        return x;
    }
};

OMG, the charm of bit operations!

posted on 2014-07-16 15:39  Tonix  阅读(144)  评论(0编辑  收藏  举报