给定一个非负整数数组,除了某个数字出现一次外,其他都出现过两次。 请找出这个唯一的数字。
输入: [4,1,2,1,2]
输出: 4
原题链接:https://leetcode-cn.com/problems/single-number/
思路直接亦或就完事了。
x ^ x = 0
x ^ 0 = x
- 复杂度分析
- 时间复杂度 O(n)。
- 空间复杂度 O(1)。
class Solution {
public:
int singleNumber(vector& nums) {
int x = 0;
for (int i = 0; i < nums.size(); i++) {
x ^= nums[i];
}
return x;
}
};



