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

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

    How about this for the sorted part, with O(logN) time complexity?

    int count(int a[], int k, int l, int h) {
      if (l>h) {
        return 0;
      }
      int mid = (l+h)/2;
      if (k > a[mid]) {
         return count(a, k, mid+1, h);
      }
      else if (k < a[mid]) {
         return count(a, k, l, mid-1);
      }
      else {
         return count(a, k, mid+1, h) + count(a, k, l, mid-1) + 1;
      }
    }
    

提交回复
热议问题