一个整数数组里面,除了两个数之外,其他的数字都出现了两次,写一个程序找出这两个数,要求算法的时间复杂度为O(n).
n为数组的长度。
程序代码如下:
//取二进制中首个为1的位置
int findFirstOne(int value)
{
int pos = 0;
while ((value&1) != 1)
{
value = value>>1;
pos++;
}
return pos;
}
//测试某位置是否为1
char testBit(int value, int pos)
{
return ((value>>pos)&1);
}
int findNums(int date[], int length, int *num1, int *num2)
{
if (length < 2)
{
return -1;
}
int ansXor=0;
int i = 0;
int pos = 0;
for (i=0; i<length; i++)
{
ansXor ^= date[i]; //异或
}
pos = findFirstOne(ansXor);
*num1 = *num2 = 0;
for(i=0; i<length; i++)
{
if (testBit(date[i], pos))
{
*num1 ^= date[i];
}
else
{
*num2 ^= date[i];
}
}
return 0;
}

在整数数组中,除两个数外其余都出现两次,利用O(n)时间复杂度的算法找到这两个数。通过异或操作找出不同数的异或结果,再定位到第一个为1的二进制位,以此区分这两个数。
476

被折叠的 条评论
为什么被折叠?



