【leetcode】Single Number

来源:互联网 发布:左程云算法视频 编辑:程序博客网 时间:2024/06/03 13:39

原题:

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?

代码:

class Solution {public:    int singleNumber(int A[], int n) {        // Note: The Solution object is instantiated only once and is reused by each test case.        if(n<0){            return -1;          }                int res = 0;          for(int i =0;i<n;i++){            res ^= A[i];          }        return res;              }};

小结:这道题之前看到过好多次,如果没有空间限制,可以用一个数组统计每个number出现的次数,得到结果。

这里有空间限制,在网上搜过后才知道可以通过异或运算实现。

这里再复习下异或运算:

1. a ^ a = 0

2. a ^ b = b ^a

3. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;

4. d = a ^ b ^ c可以推出 a = d ^ b ^ c.

5. a ^ b ^ a= b.

由交换律和结合律可知,上述解答过程正确。基础知识不扎实。。。继续努力O(∩_∩)O~ 



原创粉丝点击