LintCode 82.落单的数

题目

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

样例 1:
输入:[1,1,2,2,3,4,4]
输出:3
解释:
仅3出现一次

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


解题思路

  • 异或位运算

异或运算具有很好的性质,相同数字异或运算后为0,并且具有交换律和结合律,故将所有数字异或运算后即可得到只出现一次的数字。
^是异或运算符,异或的规则是转换成二进制比较,相同为0,不同为1.

[1,3,1]
0001 ^ 0011 ==> 0010 (1 ^ 3)
0010 ^ 0001 ==> 0011 (1 ^ 3 ^ 1 )
==>十位数 3

Solution

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

猜你喜欢

转载自blog.csdn.net/weixin_43405220/article/details/101052832