topic:
In an integer array, except for two digits, the other numbers appear two times, please write out the program to find the two occurrences of only one number, requiring time complexity O (n), space complexity of O (1). parsing:
void FindNum (int* arr, int length)
{
if (arr = = NULL | | | length < 2)
{return
;
}
int tty = arr[0];
for (int i = 1; i < length; ++i)
{
tty = Tty^arr[i];
}
At this time out of the loop, TTY for two occurrences of only one number of the difference or value
//Now need to determine the minimum bit of TTY 1 at which bit
int index = 0;
int num1 = 0;
int num2 = 0;
for (int j = 0; J < 32;++j)
{
if (tty& (1 << index)) = = (1 << index))
{
break;
}
Else
{
++index;
}
}
At this point, you need to divide the two occurrences only once into two groups for
(int p = 0; p < length; ++p)
{
if (arr[p]& (1 << index) = = (1 <& Lt Index))
{
num1 = num1^arr[p];
}
else
{
num2 = num2^arr[p];
}
}
cout << num1 << Endl;
cout << num2 << Endl;
}
void Test ()
{
int arr[] = {1, 2, 3, 4, 5, 3, 2, 1};
int length = sizeof (arr)/sizeof (arr[0));
FindNum (arr, length);
}
int main ()
{
Test ();
System ("pause");
return 0;
}