剑指 Offer 53 - I. 在排序数组中查找数字 I

剑指 Offer 53 - I. 在排序数组中查找数字 I

二分

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

        if(nums[l] != target) return 0;
        int left = l;

        l = 0;
        r = nums.length - 1;
        while(l < r){
            int mid = l + r + 1 >> 1;
            if(nums[mid] > target) r = mid - 1;
            else l = mid;
        }

        return l - left + 1;
    }
}

你可能感兴趣的:(#,剑指offer,算法)