Find a number where it appears exactly N/2 times

后端 未结 20 2147
旧巷少年郎
旧巷少年郎 2021-01-29 23:17

Here is one of my interview question. Given an array of N elements and where an element appears exactly N/2 times and the rest N/2 elements are unique

20条回答
  •  耶瑟儿~
    2021-01-29 23:36

    First off, it's past my bed time and I should know better than to post code in public without trying it first, yada, yada. I hope the criticism I'll get will at least be educational. :-)

    I believe the problem can be restated as: "Find the number that occurs more than once."

    In the absolute worst case, we would need to iterate through a little more than half the list (1 + N/2) before we found the 2nd instance of a non-unique number.

    Worst case example: array [] = { 1, 2, 3, 4, 5, 10, 10, 10, 10, 10 }

    On average though, we'd only need to iterate though 3 or 4 elements since half of the elements will contain the non-unique number i.e roughly every other number.

    Perfectly even distribution examples:

    • array [] = { 1, 10, 2, 10, 3, 10, 4, 10, 5, 10 }
    • array [] = { 10, 1, 10, 2, 10, 3, 10, 4, 10, 5 }

    In other words even if N = 1 million you would still only need to search; on average, the first 3 or 4 elements before you discovered a duplicate.

    What's the big O notation for a fixed/constant runtime that doesn't increase with N?

    Code:

    int foundAt = -1;
    
    for (int i=0; (i

提交回复
热议问题