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
题目链接:https://leetcode-cn.com/problems/single-number/
思路
肥肠典型的位运算题。
异或运算有以下三个性质:
1)任何数和 0 做异或运算,结果仍然是原来的数,即 a⊕0=a。
2)任何数和其自身做异或运算,结果是 0,即 a⊕a=0。
3)异或运算满足交换律和结合律,即a⊕b⊕a = b⊕a⊕a = b⊕(a⊕a) = b⊕0 = b。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int rec = 0;
for(int i=0; i<nums.size(); ++i){
rec ^= nums[i];
}
return rec;
}
};