Count Element Occurence

Given a sorted array of integers, find the number of occurrences of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return 0

**Example : **
Given [5, 7, 7, 8, 8, 10] and target value 8,
return 2.

思路:

做两次binary search,一次找到最左边的index,一次找到最右边的index

Solution:

Time: O(logn)
Space: O(1)

public class Solution {
    // DO NOT MODIFY THE LIST. IT IS READ ONLY
    //  0  1  2  3  4  5
    // [5, 7, 7, 8, 8, 10]
    public int findCount(final List<Integer> A, int B) {
        int l = 0;
        int left = 0;
        int right = A.size() - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (A.get(mid) >= B) {
                right = mid - 1;
            } else {
                left = mid + 1;
                l = left;
            }
        }
        // System.out.println(l);
        left = 0;
        right = A.size() - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (A.get(mid) <= B) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        // System.out.println(right);
        int result = right - l + 1;
        return result > 0 ? result : 0;
    }
}