The rookie series of C + + Classic Questions (ix)

Source: Internet
Author: User

Look for a number of unique duplicates that appear in the array

Title: 1-1000 placed in the containing 1001 An array of elements, only one element value is duplicated, and the other appears only once. Each array element can only be accessed once, design an algorithm, find it out, can you design an algorithm implementation without secondary storage space?

Method One: ( when N is relatively large alert overflow ) Add 1001 elements minus the three-way,...... 1000 The summation of the sequence, and the resulting difference is the repeating element.

int findrepeat (int *a) {    int   i;    for (i = 0; i < 1001; i++)    {        a[1000] + + a[i];    }    A[1000]-= (i* (i-1))/2;       The value of I is 1001    return   a[1000];}

Method Two:

Principle:

set the number of repetitions to A , the remaining 999 the number is different or the result is B .  

1001 the number is different or the result is a^a^b

1-1000 different or result is a^b

due to different or satisfying exchange laws and binding laws, and a^a = 0 0^a = A;

Then there are  

(a^b) ^ (a^a^b) =a^b^b=a

The implementation code is as follows:

int findrepeat (int *src, int n) {for    (int i = 1; i < n; ++i)    {        src[0] ^= (src[i] ^ i);    }    return src[0];}

Where: The SRC bit holds the array of number of elements, you are the number of element in the loop inside src[0] = src[0] ^ src[1]^...^src[n-1] ^ 1 ^ 2 ^ ... ^ (n-1)

If we can use the auxiliary space, I will have the above code:

int findrepeat (int *src, int n) {    Register int result = Src[0];    for (int i = 1; i < n; ++i)    {        result ^= (Src[i] ^ i);    }    return result;}

If there is not clear, you can contact me, if there is a mistake, please point out, to share to indicate the source, thank you

Feel good words on the top one, feel good words on the step.

The rookie series of C + + Classic Questions (ix)

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.