Find a number where it appears exactly N/2 times

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

    Peter is exactly right. Here is a more formal way of restating his proof:

    Let set S be a set containing N elements. It is the union of two sets: p, which contains a symbol α repeated N/2 times, and q, which contains N/2 unique symbols ω1..ωn/2. S = p ∪ q.

    Assume there is an algorithm that can detect your duplicated number in log(n) comparisons in the worst case for all N > 2. In the worst case means that there does not exist any subset r ⊂ S such that |r| = log2 N where α ∉ r.

    However because S = p ∪ q, there are |p| many elements ≠ α in S. |p| = N/2, so ∀ N/2 such that N/2 ≥ log2N, there must exist at least one set r ⊂ S such that |r| = log2N and α ∉ r. This is the case for any N ≥ 3. This contradicts the assumption above, so there cannot be any such algorithm.

    QED.

提交回复
热议问题