问题描述:Single Number
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?
当然最简单的方法是把这些元素放进set(集合,不能重复)中去,然后对原数组进行遍历,如果不存在就是Single Number。但这不是我们要求的最快的方法。
假设我们把数字想象当成二进制来处理问题是不是就简单多了,因为我们可以利用异或操作。下面我们简单看看异或的准则:
- 1⊕0=1
- 0⊕1=1
- 1⊕1=0
- 0⊕0=0
那我们把所有的数异或是不是就得到了Single Number,因为其他数都出现了两次。
代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int a = 0;
for(int i=0;i<nums.size();i++)
{
a ^= nums[i];
}
return a;
}
};
运行时间:
复杂度是O(n)