[LeetCode] Single Number

来源:互联网 发布:网络赚钱是真的吗 编辑:程序博客网 时间:2024/06/05 16:32

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;    }};


        

 


 



0 0