Find a number where it appears exactly N/2 times

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

    The answer is straightforward.. and can be achieved in worst case (n/2 + 1) comparisons

    1. Compare pairwise first (n-2) numbers, that is, compare nos. at 0 and 1, then 2 and 3 and so on... total n/2 -1 comparisons. If we find identical numbers in any of the above comparisons.. we have the repeated number... else:

    2. Take any one of the last two remaining numbers (say second last one I took) and compare it with the numbers in the second last pair.. if match occurs..second last no. is the repated one, else last one is the repeated one... in all 2 comparisons.

    Total comparisons = n/2 - 1 + 2 =n/2 + 1 (worst case) I dont think there is any O(log n) method to achieve this

提交回复
热议问题