您的位置:首页 > 其它

leetcode_136题——Single Number(哈希表hashtable,multiset,位运算)

2015-04-17 17:03 429 查看
#include<iostream>
//#include<bitset>
//#include<map>
#include<set>
using namespace std;

/*这道题,直接采用multiset来做,就太简单了,没啥好说的,就是全导进去,然后count下
就OK了,因为在set中查找都O(1)所以呢是线性的算法复杂度
*/
int singleNumber(int A[], int n) {
multiset<int> temp(A,A+n);
int last_result=0;
for(int i=0;i<n;i++)
{
if(temp.count(A[i])==1)
{
last_result=A[i];
break;
}
}
return last_result;
}

int main()
{
bitset<1> a;
cout<<sizeof(a)<<endl;

system("pause");
return 1;
}


  这道题还可以采用位运算的方法,就可以将时间复杂度下降到O(n)了。将所有的数都进行异或最后得到的那个结果就是只有一个数的那个数

因为 相同的两个数异或为0

0^a=a

a^a=0

之间的异或可以调换位置

即 a^b^c....=a^a^b^b^c^c......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: