[解题报告]leetcode Single Number C++

题目描述:

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?

 

要求线性复杂度和不用额外存储空间。

自己想了下没想出来,学习了discuss里其他人的方法。

初始化一个int num=0,然后用这个num和数组里的每个数都异或一遍,因为两个相同的数异或后会变成0,所以遍历到最后是0和那个单独的数异或,结果即为那个单独的数,注意到,0和0异或还是0,所以要初始化为0.

代码如下:

int singleNumber(int A[], int n)
{
    int num = 0;
    for(int i = 0; i < n; i++)
        num ^=A[i];
    return num;
}

 

posted @ 2015-04-12 13:09  Nily  阅读(140)  评论(0)    收藏  举报