For ease of Problem description, assume n = 10, that is, there are 10 numbers in array a [10], the range is from 1 to 10, and there are only two numbers with the same value. How to calculate the same value.
General idea:
1. First bubble sort, and then use the while loop to find the same value
2, directly with the idea of bubble, I from 0 to N-2, j = I + 1, in order to find the same value.
The above complexity is too high, and the special condition is not fully utilized: there are and only two values are the same.
In fact, we can sum this array a [10] = sum1, then sum from 1 to 10 = sum2, then obtain abs (sum1-sum2), and use the upper bound of this array, the value obtained from 10-abs (sum1-sum2) is the same value. Compared with the previous loop traversal, Here we only perform two summation and then do the difference. We can use the upper bound value to subtract it.
The test procedure is as follows:
[Cpp]
<Span style = "font-size: 18px;" >#include <stdio. h>
/* Calculate the sum of n elements in the array */
Int getSum1 (int a [], int n)
{
Int sum = 0;
Int I;
For (I = 0; I <n; I ++)
Sum + = a [I];
Return sum;
}
/* Calculate the sum of the numbers of consecutive B-a + 1 from a to B */
Int getSum2 (int a, int B)
{
Int sum = 0;
Int I;
For (I = a; I <= B; I ++)
Sum = sum + I;
Return sum;
}
/* Calculate the absolute value of two numbers after the difference */
Int getAbs (int a, int B)
{
Return a-B> 0? A-B: B-;
}
Int main ()
{
Int a [10] = {1, 10, 3, 4, 5, 6, 7, 8, 9, 10 };
Int sum1 = getSum2 (1, 10 );
Int sum2 = getSum1 (a, 10 );
Int ret = 10-getAbs (sum1, sum2 );
Printf ("sum1 = % d, sum2 = % d, ret = % d \ n", sum1, sum2, ret );
Return 0;
} </Span>