Efficient way to count occurrences of a key in a sorted array

后端 未结 10 1532
粉色の甜心
粉色の甜心 2021-01-30 23:49

This was asked in on-site Microsoft interview.

Count the number of occurrences of a given key in an array.

I answered linear search because the elements may be s

10条回答
  •  失恋的感觉
    2021-01-31 00:16

    If the array is unsorted, yes, linear search from one end to the other is as good as it gets.

    However, if the array is sorted, you can do better than linear time by applying binary or interpolation search techniques.

    Treat the problem as the same as "Find the number X in a sorted list" with the added detail of "then scan left and right to determine how many times X appears". The first part, the search, is best done with binary or interpolation search in most cases.

    http://en.wikipedia.org/wiki/Interpolation_search

    http://en.wikipedia.org/wiki/Binary_search

提交回复
热议问题