剑指Offer (二分法的运用)数的出现次数,O(logN)

剑指Offer (二分法的运用)数的出现次数,O(logN)_第1张图片

class Solution {
     
    public int search(int[] nums, int target) {
     
        if (nums == null || nums.length == 0) return 0;
        int l = 0,r = nums.length - 1;
        while (l < r) {
     
            int mid = l + r >> 1;
            if (nums[mid] >= target) r = mid;
            else l = mid + 1;
        }
        int left = l;
        if (nums[l] != target) return 0;
        else{
     
            l = 0;
            r = nums.length - 1;
            while (l < r) {
     
                int mid = l + r + 1 >> 1;
                if (nums[mid] <= target) l = mid;
                else r = mid - 1; 
            }
        int right = l;
        int res = right - left + 1;
        return res;
        } 
    }
}

剑指Offer (二分法的运用)数的出现次数,O(logN)_第2张图片

你可能感兴趣的:(剑指Offer,二分法,二分查找,java,算法)