简体   繁体   中英

Given an array of +ve integers, Find the number which occurs odd number of times in O(n) time & constant space.

Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.

int getOddOccurrence ( int ar[]){
    int i;
    int res = 0;
    for (i = 0; i < ar.size; i++)
        res = res ^ ar[i];
    return res;
}

/* Diver function to test above function */
PSVM() {
    int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
    SOP(getOddOccurrence(ar));
}

Approach 1: By X-OR ing all the elements in an array

I am trying to x-or all the elements. Is that the
correct approach? Above is the code using X-OR

Approach 2: By using HashMap If I use hashmap , the space complexity would be O(n). Which is not good.

Which approach should I use?

This problem assumes there is only one number which occurs odd number of
times in the array. If you have more such numbers - say K of them: a1, a2, ... aK ,
then at the end of the loop, in res you will get this value.

res == a1 ^ a2 ^ ... ^ aK

From that value you cannot infer/extract all K unknown numbers a1, a2, ... aK .

Buf ... you see, if K=1 (ie if you have exactly one number occurring
odd number of times), at the end you will get in res just that number.

Use the first approach as long as you understand why it works.

Also, in the second approach the space is not O(n) but O(s) ,
where s is the count of distinct values in your array. And as you
have only 1 number occurring odd number of times we can say for sure
that 2*s + 1 <= n ie s <= (n-1)/2 . So the space complexity
is O((n-1)/2) in the second approach. You achieve it when your array
looks like this: s numbers occurring twice, and 1 number occurring once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM