题目:
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,0和别的数字异或还是原来的数,那么只有一个数字是一次,其他数字都是两次,那么将所有的数字异或,最终剩下的就是出现一次的那个数字。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
一个数组中只有一个数字是出现了一次 其他都是出现了两次
找到这个出现一次的数字
*/
int SingleNumber(vector<int>& vec)
{
if(vec.size()<=0)
return 0;
int i;
int value = vec[0];
for(i=1;i<vec.size();i++)
value ^= vec[i];
return value;
}
int main()
{
int array[]={12,23,12,45,56,45,23};
vector<int> vec(array,array+sizeof(array)/sizeof(int));
cout<<SingleNumber(vec);
return 0;
}