When the integer number in the array is continuous, calculate the unique repeated integer in the array.

Source: Internet
Author: User

In real life, I guess this problem doesn't make much sense. But as a method, you can also draw a conclusion, that is, to apply mathematics knowledge to programming as much as possible, the algorithm will be perfect. /*************************************** **************************************** **************************************** * ************ 1: problem description: given an array of 101 elements, the elements in the array must belong to [1,100], and each number between [1,100] exists in arr. 2: solution: for analysis, the array contains 101 elements. If each number between [1,100] appears once, it is 100 elements, the remaining element is the unique repeated element. We can traverse arr to get the total number of all elements in arr. Since each number between [1,100] appears once, then we subtract 1 + 2 + ...... + 99 + 100 of the sum, the result is the unique recurring element we need. The time complexity is O (n ). **************************************** **************************************** **************************************** *************/

// Recursive sum of array elements int sum (int a [], int length) {int result = 0; if (length = 1) {result = a [0];} else {result = sum (a, length-1) + a [length-1];} return result;} // use the equals sequence to obtain the sum of 1---100, then subtract it. Int getrepeated (int a []) {int temp1 = (1 + 100) * 100/2; int temp2 = sum (a, 101); return temp2-temp1 ;}

 


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.