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?
给个简单的翻译:
给一个整数数组,出一个例外,其他数均出现两遍,找出这个单一的数。
要求线性时间复杂度,同时空间复杂度为O(1),即只允许开常数个空间。
这次依然是先上答案
class Solution {
public:
int singleNumber(vector<int>& nums) {
int a = 0;
for (int i = 0; i<nums.size(); i++)
{
a ^= nums[i];
}
return a;
}
};
运用亦或的性质。
^:相同为0,不同为1。
1—a^a=0;
2—a^0=0;
3—a^b=b^a;(交换律)
知道了亦或的用法,对于上述题,就可以想到:
如果将所有数字全亦或起来,运用“3”,把相同的两个数合并起来,运用“1”,将他们变为0,最后运用“2”,消掉两两相同的部分,就得到(single dog(呸))单一数。
在电脑上查了亦或的妙用,发现了一道很相似但更难的题目,先给出网址:
http://blog.csdn.net/sunmenggmail/article/details/7776848
给你1-1000个连续自然数,然后从中随机去掉两个,再打乱顺序,要求只遍历一次,求出被去掉的两个数。