Determine the most common occurrence in an array

前端 未结 9 987
南方客
南方客 2020-11-29 12:28

Assume I have an array of doubles that looks like the following:

Array[10] = {10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10}

I need a function th

9条回答
  •  猫巷女王i
    2020-11-29 12:41

    Sort the array first w/ quick sort and then scan and count for a majority - O(n ln n). If the range of elements is known ahead of time, say between {1,k}, then a counting sort can be used which will run in O(n+k).

    As a slight improvement, as you are scanning the sorted array, if you find value that has more that n/2 occurrences you are done.

提交回复
热议问题