[Leetcode 136, Medium] Single Number I

来源:互联网 发布:网络骗局有哪些 编辑:程序博客网 时间:2024/06/06 08:48

Problem:

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?

Analysis:

算法:逻辑运算的异或(^)是交换且可结合的,而且,是幂等的。所以,如果是有且只有一个单独出现的元素,那么把所有的元素进行异或操作,所得到的值就是所要的结果。

衍生问题:every element appears even times except for one which appears odd times.

Solution

C++:

(I)

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