给你n个数,其中有且仅有两个数出现了奇数次,其余的数都出现了偶数次。用线性时间常数空间找出出现了奇数次的那两个数。
// in case find one missing number, here size is 1 less than the range n
int find_missing_number1 (int a[], int size)
{
int number=0;
for (int i=0;i<size;i++)
number ^= ((i+1)^a[i]);
number ^= (size+1);
return number;
}
// in case find one missing number, here size is 1 less than the range n
int find_missing_number1 (int a[], int size)
{
int number=0;
for (int i=0;i<size;i++)
number ^= ((i+1)^a[i]);
number ^= (size+1);
return number;
}
// in case find two missing numbers, here size is 2 less than the range n
void find_missing_number2 (int a[], int size, int& miss1, int& miss2)
{
miss1 = 0;
miss2 = 0;
int number=0;
for (int i=0;i<size;i++)
number ^= ((i+1)^a[i]);
number ^= (size+1);
number ^= (size+2);
// now number will be miss1^miss2
// find the binary 1 in number
int k = number - (number&(number-1));
for (int i=0;i<size;i++)
{
if ( (i+1)&k )
miss1 ^= (i+1);
if ( a[i]&k )
miss1 ^= a[i];
}
if ( (size+1) & k )
miss1 ^= size+1;
if ( (size+2) & k )
miss1 ^= size+2;
miss2 = number ^ miss1;
}
// in case find two missing numbers, here size is 2 less than the range n
void find_missing_number2 (int a[], int size, int& miss1, int& miss2)
{
miss1 = 0;
miss2 = 0;
int number=0;
for (int i=0;i<size;i++)
number ^= ((i+1)^a[i]);
number ^= (size+1);
number ^= (size+2);
// now number will be miss1^miss2
// find the binary 1 in number
int k = number - (number&(number-1));
for (int i=0;i<size;i++)
{
if ( (i+1)&k )
miss1 ^= (i+1);
if ( a[i]&k )
miss1 ^= a[i];
}
if ( (size+1) & k )
miss1 ^= size+1;
if ( (size+2) & k )
miss1 ^= size+2;
miss2 = number ^ miss1;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = { 1,2,4,5,9,7,8,10,3 };
int b[] = { 1,2,4,5,9,7,6,11,3,10 };
int s1,s2;
int k = find_missing_number1(a,sizeof(a)/sizeof(a[0]));
find_missing_number2(b,sizeof(b)/sizeof(b[0]),s1,s2);
std::cout<<"missing number 1 is "<<k<<std::endl;
std::cout<<"missing number 2 is "<<s1 << " and "<<s2<<std::endl;
system("pause");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = { 1,2,4,5,9,7,8,10,3 };
int b[] = { 1,2,4,5,9,7,6,11,3,10 };
int s1,s2;
int k = find_missing_number1(a,sizeof(a)/sizeof(a[0]));
find_missing_number2(b,sizeof(b)/sizeof(b[0]),s1,s2);
std::cout<<"missing number 1 is "<<k<<std::endl;
std::cout<<"missing number 2 is "<<s1 << " and "<<s2<<std::endl;
system("pause");
return 0;
}