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

题目

法1:二分查找,最佳解法!!!

class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        int n = nums.length;
        int left = findLeftBoundary(nums, target, 0, n - 1);
        int right = findRightBoundary(nums, target, 0, n - 1);
        if (left <= right) {
            return new int[]{left, right};
        }

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

    public int findLeftBoundary(int[] nums, int target, int start, int end) {
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] >= target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }

        return start;
    }


    public int findRightBoundary(int[] nums, int target, int start, int end) {
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] <= target) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }

        return end;
    }
}

你可能感兴趣的:(二分查找)