Unique duplicate Element

Source: Internet
Author: User

Unique duplicate Element

Problem description: Set ~ 1000 is placed in an array containing 1001 elements. Only one unique element is repeated, and all other elements appear once. Design an algorithm to find out the unique and repeated element. Each array element must be accessed only once and cannot use auxiliary storage space.

 Solution 1: Based on the topic description, you only need to sum the number of 1001 in the array to get sum0, And then subtract the sum of 1 to 1000 and sum1 to get the unique repeated number.

Reference code:

# Include <bits/stdc ++. h> using namespace std; int main () {srand (time (NULL); int pos = rand () % 1002; int num = rand () % 1002; cout <"random numbers:" <num <endl; int sum0 = 0; int sum1 = 0; for (int I = 1; I <= 1000; I ++) {if (I = pos) {sum0 + = num; sum0 + = pos;} else {sum0 + = I;} sum1 + = I ;} cout <"unique duplicate number:" <sum0-sum1 <endl ;}

GCC running result:

Solution 2:

This method is based on the difference or a ^ B ^ a = B; then we can make the occurrence of two times more than once, and the appearance of one more time for the same or, that is, a ^ B ^ a ^ B =;

(Because a ^ B ^ a = B ^ a ^ B =)

Reference code:

# Include <bits/stdc ++. h> using namespace std; int findRepeat (const int a []) {int temp = a [0]; for (int I = 1; I <1001; I ++) {temp ^ = I; temp ^ = a [I];} return temp;} int main () {srand (time (NULL); int num = rand () % 1002; cout <"random number:" <num <endl; int a [1001]; memset (a, 0, sizeof ()); a [0] = num; for (int I = 1; I <1001; I ++) {a [I] = I ;} cout <"the only repeated number is:" <findRepeat (a) <endl ;}

GCC running result:

We hope to find other solutions.

Reprinted Please note: http://www.cnblogs.com/zpfbuaa

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.