Most common element in an array / Finding the relative majority, deterministically in O(n) time and O(1) space?

后端 未结 4 1298
暗喜
暗喜 2021-01-17 17:18

So for example, the answer for the array:

1, 11, 3, 95, 23, 8, 1

would be 1, since all the other elements only occur once while 1 occurs twice.

A lo

4条回答
  •  没有蜡笔的小新
    2021-01-17 17:39

    Use the idea from here:

    How can we find a repeated number in array in O(n) time and O(1) space complexity

    And apply a technique similar to counting sort. That is, create N bins (an array of size N), where N is the largest integer you expect to encounter. This is still O(1) space. Then, iterate through the original array in O(n) time, and when you encounter a value i, increment your results array at index i by 1. Then, iterate through the results array (again O(1) time), finding the largest single value. The index of that value will be the most common value in the original list.

提交回复
热议问题