Find a number where it appears exactly N/2 times

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

    There is a constant time solution if you are ready to accept a small probability of error. Randomly samples two values from the array, if they are the same, you found the value you were looking for. At each step, you have a 0.75 probability of not finishing. And because for every epsilon, there exists one n such that (3/4)^n < eps, we can sample at most n time and return an error if we did not found a matching pair.

    Also remark that, if we keep sampling until we found a pair, the expected running time is constant, but the worst case running time is not bounded.

提交回复
热议问题