Find a number where it appears exactly N/2 times

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

    I think you simply need to parse through the array keeping a backlog of two elements. As N/2 are equal and the rest is guaranteed to be distinct there must be one place i in your array where

    a[i] == a[i-1] OR a[i] == a[i-2]

    iterate once through your array and you have complexity of roughly 2*N which should be well inside O(N).

    This answer is somewhat similar to the answer by Ganesh M and Dougie, but I think a little simpler.

提交回复
热议问题