您的位置:首页 > 其它

[LeetCode] Single Number

2014-10-27 10:18 330 查看
Given an array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
思路:异或操作符有个这样一个性质:两个相同的数异或后结果为0,0^A = A,并且满足交换律。


比如 A^B^C^B 等价于 A^C。这一性质常用于寻找成对出现时,缺失的某一个数。

如果有一组数,A、B、C、A、B 则A^B^C^A^B = D,即D快速出现了一次。

使用异或操作符能够满足,此题要求的时间复杂度为O(n), 空间复杂度O(1)。

class Solution {
public:
    int singleNumber(int A[], int n) {
       
       int result = 0;
       
       for (int i = 0; i < n; ++i) {
           result ^= A[i];
       }
       
       return result;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: