力扣34. 在排序数组中查找元素的第一个和最后一个位置

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[]{-1,-1};
        if(nums == null || nums.length == 0) return res;
        int leftIndex = findTarget(nums,target,true);
        if(leftIndex == nums.length || nums[leftIndex] != target) return res;
        res[0] = leftIndex;
        res[1] = findTarget(nums,target,false)-1;
        return res;
    }
    //isLeft为true,返回下标为最左边下标
    //isLeft为false,返回下标为最右边下标+1
    private int findTarget(int[] nums,int target,boolean isLeft){
        int l = 0;
        int h = nums.length;
        while(l < h){
            int m = l + (h - l)/2;
            if(nums[m] > target || (isLeft && nums[m] == target)) h = m;
            else{
                l = m + 1;
            }
        }
        return l;
    }
}

猜你喜欢

转载自www.cnblogs.com/come-on-pxw/p/12790929.html