1,题目要求
Given a non-empty 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?
给定一个非空的整数数组,除了一个元素外,每个元素都会出现两次。 找一个单一的。
注意:
您的算法应具有线性运行时复杂性。 你能不用额外的内存来实现吗?
2,题目思路
对于这道题,要求的是求一个数组中只出现一次的数字。
如果利用额外的空间来计算,是非常简单的,只需要对数组遍历以便,统计每个数字出现的次数,就可以得到最后结果了。
但是题目要求不用额外的空间,因此,这里又用到了位运算的特性。
在位运算的中,异或(XOR) 有个特殊的特点:
- a ^ b = c;
- c ^ a = b;
即:
- a ^ a = 0;
- 0 ^ b = b;
在这道题中,重复的数字只会两两出现,单独的数字只有一个,因此,当我们将所有的数字都进行了异或之后,就可以得到那个单独的数字了。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.size() == 0)
return 0;
int res = nums[0];
for(int i = 1;i<nums.size();i++)
res ^= nums[i];
return res;
}
};