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

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

    package arrays;

    /* * Given a sorted array, find the number of times an element occured. * Binary search O(lgn) * */

    public class NumberOfN {

    static int bSearchLeft(int[] arr, int start, int end, int n){
    
        while(start < end){
    
            int mid = (start + end)>>1;
            if(arr[mid] < n){
                start = mid + 1;
            }else{
                end = mid;
            }
    
        }
    
        return end;
    }
    
    static int bSearchRight(int[] arr, int start, int end, int n){
    
        while(start < end){
    
            int mid = (start + end)>>1;
            if(arr[mid] <= n){
                start = mid + 1;
            }else{
                end = mid;
            }
    
        }
    
        return end;
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
    
        int[] arr = new int[]{3,3,3,3};
        int n = 3;
        int indexLeft = bSearchLeft(arr, 0, arr.length, n);
        int indexRight = bSearchRight(arr, 0, arr.length, n);
        System.out.println(indexLeft + " " +indexRight);
        System.out.println("Number of occurences: " + (indexRight - indexLeft));
    }
    

    }

提交回复
热议问题