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

发布时间:2023年12月19日

题目
剑指中重题

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