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

2023-12-29 21:16:36

题目

法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;
    }
}

文章来源:https://blog.csdn.net/Allenlzcoder/article/details/135297299
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。