LintCode 82. 落单的数

题目:落单的数


要求:

给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。

样例:

给出 [1,2,2,1,3,4,3],返回 4

算法要求:

一次遍历,常数级的额外空间复杂度

解题思路:

我们只需要找出出现了一次的数字。
题中指出,只有一个数只出现过一次,那么我们只需要找到一个方法,放出现二次的数相除抵消,即相同的数相互抵消。
那我们就想起了位操作符中的异或

算法如下:

class Solution {
public:
    /*
     * @param A: An integer array
     * @return: An integer
     */
    int singleNumber(vector<int> &A) {
        // write your code here
        int a = 0;
        for(int i=0; i<A.size(); i++)
            a ^= A[i];
        return a;
    }
};

猜你喜欢

转载自blog.csdn.net/linglian0522/article/details/78594260