容易_82_落单的数(5)

来源:互联网 发布:水质监测数据 编辑:程序博客网 时间:2024/06/05 03:03

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


样例

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


思路:通过异或,相同的数结果为0,那么最后的结果一定是落单的数字。


解题关键:

1.一个数与自身异或的结果为0

2.异或满足交换律

3.任何数与0的异或为其本身


http://www.cnblogs.com/hujunzheng/p/5045084.html


参考代码:

class Solution {public:    /**     * @param A: Array of integers.     * return: The single number.     */    int singleNumber(vector<int> &A) {        // write your code here        int ans = 0;        for(int i=0; i<A.size(); ++i)            ans ^= A[i];        return ans;    }};

原创粉丝点击