题目英文描述:
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?
题目中文描述:
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
思路:异或运算能满足O(1),异或运算满足交换律和结合律,即a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b,因此最终结果一定是只出现一次的那个数。
代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
for(auto num : nums) result ^= num;
return result;
}
};