Find a number where it appears exactly N/2 times

后端 未结 20 2192
旧巷少年郎
旧巷少年郎 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:51

    Restating my solution from a comment to Ganesh's version so I can format it:

    for (i=0; i

    Probability of winning after 1 iteration: 50%

    Probability of winning after 2 iterations: 75%

    Etc.

    Worst case, O(n) time O(1) space.

    Note that after N/4 iterations you've used up all the N/2 unique numbers, so this loop will never iterate through more than 3/4 of the array if it is as specified.

提交回复
热议问题