Algorithm Design: There are n numbers ranging from 1 to n, and only two unique numbers are the same. How can we obtain the same value as quickly?

Source: Internet
Author: User

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>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.