136. Single Number
Difficulty: Medium
Given an 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?
思路
元素与自身异或,结果为0。
vector中所有元素异或,由于除了一个元素只出现一次,其余元素都出现两次,计算结果为出现单次的元素。
代码
[C++]
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for(vector<int>::iterator it = nums.begin(); it != nums.end(); ++it)
res ^= *it;
return res;
}
};