LintCode Single Number III

Given 2*n + 2 numbers, every numbers occurs twice except two, find them.
Have you met this question in a real interview? Yes
Example
Given [1,2,2,3,4,4,5,3] return 1 and 5
Challenge
O(n) time, O(1) extra space.

class Solution {
public:
    /**
     * @param A : An integer array
     * @return : Two integers
     */
    vector<int> singleNumberIII(vector<int> &A) {
        // write your code here
        int xors = 0;
        for (int e : A) {
            xors ^= e;
        }

        int a = 0, b = 0;

        int offset = 31;
        while (offset >= 0 && ((xors >> offset) & 0x1) == 0) {
            offset--;
        }

        for (int e : A) {
            if (0x1 & (e>>offset)) {
                a ^= e;
            } else {
                b ^= e;
            }
        }

        return {a, b};
    }
};

首先进行一次全部数据的xor,这样的结果就是两个只出现一次的数的xor结果,由于两个数必然是不同的,所以他们xor结果上的某一个位必然是1,依据这个特征再将数分成两组,分别求出各自组内的xor,结果就是只出现一次的数。分组也可以按如下进行

        int mask = xors ^ (xors & (xors - 1));

        for (int e : A) {
            if (e & mask) {
                a ^= e;
            } else {
                b ^= e;
            }
        }
posted @ 2015-09-17 16:18  卖程序的小歪  阅读(106)  评论(0编辑  收藏  举报