标签:style blog http io os ar strong for 2014
LeetCode上面有这样两道Single Number 问题:
1、假设一个整型数组中所有的元素都出现了两次,唯独只有一个元素出现了一次,求出这个出现一次的元素。
2、假设一个整型数组中所有的元素都出现了三次,唯独只有一个元素出现了一次,求出这个出现一次的元素。
显然,两个问题唯一的不同就是大部分元素是出现了两次还是三次。
对于问题1:很好解决,通过异或运算,我们可以把所有出现两次的元素消除 a^a = 0; 最后就只剩下那个出现一次的元素了 0^b = b。
int singleNumber(int A[], int n)
{
int result=0;
for(int i=0; i<n; i++)
{
result ^= A[i];
}
return result;
}
int singleNumber(int A[], int n)
{
int a[32] = {0};
int result=0;
for(int i=0; i<32; i++)
{
for(int j=0; j<n; j++)
{
if((A[j]>>i)&0x1 == 1) a[i]++;
}
result |= ((a[i]%3)<<i);
}
return result;
}
标签:style blog http io os ar strong for 2014
原文地址:http://blog.csdn.net/crayondeng/article/details/39289387