题目描述

统计一个数字在排序数组中出现的次数

Input:
nums = 1, 2, 3, 3, 3, 3, 4, 6
K = 3

Output:
4

解题思路

class Solution {
    public int search(int[] nums, int target) {
        if(nums == null || nums.length == 0)
            return 0;
        
        // 二分 
        int star = binarySearch(nums, target), end = binarySearch(nums, target+1);
        // 考虑target和target+1,将两个起始位置相减。注意end-star+(1|0)
        return end - star + (nums[end] == target ? 1 : 0);
    }

    // 二分
    private static int binarySearch(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        
        while(l < r) {
            int mid = l + (r - l) / 2;
            // [l mid] [mid+1, r]
            if(nums[mid] < target)
                l = mid + 1;
            else
                r = mid;
        }
        return l;        
    }
}