Find a number where it appears exactly N/2 times

后端 未结 20 2152
旧巷少年郎
旧巷少年郎 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条回答
  •  萌比男神i
    2021-01-29 23:32

    Similar to https://stackoverflow.com/a/1191881/199556 explanation.

    Let's compare 3 elements(3 comparison operation) in worse case "same" element will appear once. So we reduce the tail by 3 and reduce count of "same" elements by one.

    In final step(after k iterations) our tail will contain (n/2) - k "same" elements. Let's compare the length of the tail.

    On the one hand it will n-3k on the other hand (n/2) - k + 1. Last unsame elements may exist.

    n-3k = (n/2) - k + 1

    k = 1/4*(n-2)

    After k iterations we'll surely get result.

    Number of comparisons 3/4*(n-2)

提交回复
热议问题