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

后端 未结 10 1547
粉色の甜心
粉色の甜心 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:27

    For once, I will propose an implementation in C++.

    size_t count(std::vector const& vec, int key)
    {
      auto p = std::equal_range(vec.begin(), vec.end(), key);
      return std::distance(p.first, p.second);
    }
    

    equal_range uses a binary search, the result is equivalent to:

    std::make_pair(std::lower_bound(vec.begin(), vec.end(), key),
                   std::upper_bound(vec.begin(), vec.end(), key));
    

    but the implementation should makes it slightly faster, even though all are in O(log N) (in terms of number of comparison).

提交回复
热议问题