数组中只出现一次的数字

题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)

// Find two numbers which only appear once in an array

// Input: data - an array contains two number appearing exactly once,

//               while others appearing exactly twice

// Output: num1 - the first number appearing once in data

//         num2 - the second number appearing once in data

staticvoid FindNumsAppearOnce(int[] arr, outint num1, outint num2)

{

num1 = num2 = 0;

 

 

if (arr.Length < 2)

{

 

 

return;

}

 

 

// get num1 ^ num2

int resultExclusiveOR = 0;

for (int i = 0; i < arr.Length; ++i)

{

resultExclusiveOR ^= arr[i];

}

 

 

// get index of the first bit, which is 1 in resultExclusiveOR

int indexOf1 = FindFirstBitIs1(resultExclusiveOR);

for (int j = 0; j < arr.Length; ++j)

{

 

 

// divide the numbers in data into two groups,

// the indexOf1 bit of numbers in the first group is 1,

// while in the second group is 0

if (IsBit1(arr[j], indexOf1) ==1)

num1 ^= arr[j];

 

 

else

num2 ^= arr[j];

}

}

 

 

// Find the index of first bit which is 1 in num (assuming not 0)

staticint FindFirstBitIs1(int num)

{

 

 

int indexBit = 0;

while (((num & 1) == 0) && (indexBit < 32))

{

num = num >> 1;

++indexBit;

}

 

 

return indexBit;

}

 

 

// Is the indexBit bit of num 1?

staticint IsBit1(int num, int indexBit)

{

num = num >> indexBit;

 

 

return num & 1;

}

posted @ 2014-01-08 16:58  purplesun  阅读(136)  评论(0编辑  收藏  举报