Find a number where it appears exactly N/2 times

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

    To do it less than O(n) you would have to not read all the numbers.
    If you know there is a value that satisifies the relationship then you could just sample a small subset an show that only one number appears enough times to meet the relationship. You would have to assume the values are reasonably uniformly distributed

    Edit. you would have to read n/2 to prove that such a number existed, but if you knew a number existed and only wanted to find it - you could read sqrt(n) samples

提交回复
热议问题