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

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

    ** Time Complexity = O ( lg N ) where N is the size of array

    ** Arguments for binarySearchXXXXX:**

    1. int[] array is a sorted array of length >= 1
    2. int k : key to search

    **

    package array;
    
     public class BinarySearchQuestion {
    
    public static int binarySearchFirst(int[] array, int k) {
        int begin = 0;
        int end = array.length-1;
        int mid = -1;
        while (begin <= end) {
            mid = begin + (end - begin) / 2;
            if (array[mid] < k) {
                begin = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        //System.out.println("Begin index :: " + begin + " ,  array[begin] " + array[begin]);
        return (begin <= array.length - 1  && begin >= 0 && array[begin] != k) ? -1 : begin;
        //      return begin;
    }
    
    public static int binarySearchLast(int[] array, int k) {
        int begin = 0;
        int end = array.length - 1;
        int mid = -1;
        while (begin <= end) {
            mid = begin + (end - begin) / 2;
            if (array[mid] > k) {
                end = mid - 1;
            } else {
                begin = mid + 1;
            }
        }
        //System.out.println("Last index end :: " + end + " ,  array[mid] " + array[end]);
        return (end <= array.length - 1  && end >= 0 &&  array[end] != k) ? -1 : end;
        //return end;
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
                 //     int[] array = { 0, 1,1,1, 2, 3, 4,4,4,5, 5, 5, 5, 5, 5, 5, 5, 5, 5,5,6,6,6,6, 6, 7, 7, 7,
                 //             7, 8, 9 };
                //      int[] array = {-1, 0,1, 1,1,2,3};
        int[] array = {1,1,1};
    
        int low = binarySearchFirst(array, 1);
        int high = binarySearchLast(array, 1);
        int total = (high >= low && low != -1 && high != -1) ? ( high - low + 1 ): 0;
        System.out.println("Total Frequency " + total);
    }
    
       }
    

提交回复
热议问题