LeetCode 34 二分查找区间

//分别找最左边和最右边



class Solution {
    public int[] searchRange(int[] nums, int target){
        if (nums.length == 0)   return new int[]{-1, -1};
        int left = searchLeft(nums, target);
        int[] res = new int[2];
        if (left == -1){
            res[0] = -1;
            res[1] = -1;
            return res;
        }
        int right = searchRight(nums, target);
        if (left < right){
            res[0] = left;
            res[1] = right;
        }else {
            res[0] = right;
            res[1] = left;
        }

        return res;
    }

    public int searchLeft(int[] nums, int target){
        int left = 0;
        int right = nums.length;
        int mid = 0;
        while (left < right - 1){ // 左闭右开
            // System.out.println(left + " " + right);

            mid = (left + right) / 2;
            if (target > nums[mid])
                left = mid + 1;
            else if (target == nums[mid])
                left = mid;
            else 
                right = mid;

        }

        if (left < nums.length && nums[left] == target)
            return left;
        return -1;
    }

    public int searchRight(int[] nums, int target){
        int left = -1;
        int right = nums.length - 1;
        int mid = 0;
        while(left + 1 < right){ // 左开右闭
            // System.out.println(left + " " + right);
            mid = (left + right) / 2;
            if (target < nums[mid])
                right = mid - 1;
            else if (target == nums[mid])
                right = mid;
            else 
                left = mid;
        }
        
        if (right >= 0 && nums[right] == target)
            return right;
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/TIMELIMITE/article/details/89786071
今日推荐