题目
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?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
思路
一个数与自己的异或为0,一个数与0的异或为其本身。
异或运算本身具有交换律,因此,如果一个数组中每个数字都出现了两次,那么逐一异或得到的结果为0。而按题目中的描述,输入的数组比上述数组多了一个数,那么逐一异或的结果就等于0异或该数,即该数本身。
因此,我们只需要逐一异或就可以得到这个只出现一次的数了。
代码
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for(auto num : nums)
res ^= num;
return res;
}
};
感想
位运算的题目真是一点也想不出思路,这题完全是百度出的答案,感觉这方面需要好好练练。