LeetCode-Array-【34】在排序数组中查找元素的第一个元素和最后一个元素(Java)

题目描述:

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

你的算法时间复杂度必须是 O(log n) 级别。

如果数组中不存在目标值,返回 [-1, -1]。

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]

方法:

二分法解题:
  • 因为题目要求时间复杂度为:O(log n) ,故需要采用二分法进行查找target在数组中的第一个位置和最后一个位置
  • 要注意的时因为我们初始化 right = nums.length
    所以决定了我们的「搜索区间」是 [left, right)
    所以决定了 while (left < right)
    同时也决定了 left = mid + 1 和 right = mid
详细代码:
class Solution {
    
    
    public int[] searchRange(int[] nums, int target) {
    
    
        int[] res = {
    
     -1, -1 };
        if(nums.length==0) return res;
        boolean flag = true;
        int leftIndex = boundIndex(nums, target, flag);
        //leftIndex == nums.length代表target不存在
        if (leftIndex == nums.length||nums[leftIndex] != target)
            return res;
        res[0] =leftIndex;
        res[1] = boundIndex(nums, target, false)-1;
        return res;
    }

    public int boundIndex(int[] nums, int target, boolean flag) {
    
    
        int low = 0, high = nums.length;
        while (low < high) {
    
    
            int mid = (low + high) / 2;
            //递归mid左边的数列
            if (target < nums[mid] || (flag &&(target == nums[mid]))) {
    
    
                high = mid;
            } else {
    
    
                low = mid + 1;
            }
        }
        return low;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41291067/article/details/102942779
今日推荐