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?
数组含有n个数,其中有一个数只出现1次,其余的数都出现两次,求只出现一次的数。
这个主要考察的是位运算中的异或运算的性质-----当两个相等的数做异或运算他们的值为0(a^a = 0)。本题中对数组中所有的数做异或,那么最后异或的结果就是只出现1次的数。思想很简单代码如下。
class Solution { public: int singleNumber(int A[], int n) { if(A==NULL || n<=0) return 0; int ret = A[0]; for(int i=1; i<n; ++i) ret ^= A[i]; return ret; } };
[ LeetCode] Single Number,布布扣,bubuko.com
原文:http://blog.csdn.net/swagle/article/details/28388241