Single Number
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?
数组里面每一个元素出现2次,只有一个元素出现一次,输出它。利用异或运算解题。
将全部的数异或,相同的数,异或结果为0 ,所以最后只剩下那个只出现一次的数
class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int>::iterator p=nums.begin();
int s=0;
for(;p!=nums.end();p++)
s=s^(*p);
return s;
}
};