【重点】【二分查找】34. 在排序数组中查找元素的第一个和最后一个位置

题目
剑指中重题

法1:二分查找

注意:寻找完边界后,要判断两者是否合法!!!

class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        int leftBound = findLeftBound(nums, target, 0, nums.length - 1);
        int rightBound = findRightBound(nums, target, 0, nums.length - 1);
        if (leftBound <= rightBound) {
            return new int[]{leftBound, rightBound};
        }

        return new int[]{-1, -1};
    }

    public int findLeftBound(int[] nums, int target, int left, int right) {
        int mid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return left;
    }

    public int findRightBound(int[] nums, int target, int left, int right) {
        int mid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return right;
    }
}

你可能感兴趣的:(力扣Top100,二分查找)