Array A [n], stores 1 to the number of N-1, where A number repeats once. Write a function to find the number of duplicates |
The time complexity must be the O (n) function prototype:
Method 1:
# Include <iostream>
Using namespace STD;
Int main ()
{
Int A [] = {1, 2, 4, 5, 6, 8, 8 };
Int n = sizeof (a)/sizeof (INT );
Int J = n-1;
For (INT I = 0; I <n & J> I ;)
{
If (A [I]! = A [J])
{
J --;
If (j = I + 1)
{
I + = 1;
J = n-1;
}
}
If (A [I] = A [J])
{
Cout <"Location:" <I <"value:" <A [I] <Endl;
Break;
}
}
Return 0;
}
Method 2: Use the number in the array to remove the sum of non-repeating numbers and the number is repeated.
# Include <iostream>
Using namespace STD;
Int main ()
{
Int A [] = {1, 2, 4, 5, 6, 8, 8 };
Int n = sizeof (a)/sizeof (INT );
Int sum1 = 0, sum2 = 0;
For (INT I = 0; I <n; I ++)
{
Sum1 + = A [I];
}
Sum2 = n-1 + (n-1) * (n-2)/2;
Cout <(sum1-sum2) <Endl;
Return 0;
}