Single Number

来源:互联网 发布:网络教育全国统考难吗 编辑:程序博客网 时间:2024/06/08 13:16

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?

给定一组整数,出了一个数外其他整数全部都出现了两次。
Note:
你的算法必须是线性的时间复杂度,你能不用额外的空间的么?
方法很简单,运用异或运算。
异或运算满足交换律,当两数相同时为0,不同时为1。所以所有有两个的数异或之后都为0了,最后再跟最后一个single异或则得到那个single。
代码如下:
class Solution {public:    int singleNumber(int A[], int n) {        int result=0;        for(int i=0;i<n;i++)        {           result=result^A[i];        }        return result;    }};


0 0