Leetcode 题解 --二分查找--查找区间

[LeetCode] Search for a Range 搜索一个范围

 

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

 

这道题让我们在一个有序整数数组中寻找相同目标值的起始和结束位置,而且限定了时间复杂度为O(logn),这是典型的二分查找法的时间复杂度,所以这道题我们也需要用此方法,我们的思路是首先对原数组使用二分查找法

使用两次二分查找法,第一次找到左边界,第二次调用找到右边界即可

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] ret = new int[2];
        Arrays.fill(ret, - 1);
        if(nums.length == 0)
            return ret;
        int l = 0, h = nums.length - 1;
//找左边界,让l变化 h不断从右边靠拢至左边,l正好停在l=h =左边界上  比如88888
        while(l < h){
            int m = l + (h-l) / 2;
            if(nums[m] < target){
                l = m + 1;
            }
            else
                h = m;
                
        }
//说靠拢之后 l=h != target  不存在左边界说明没有一个与target相等的值 即没有等于target的值 说明不存在目标值
        if(nums[h] != target)
            return ret;【-1, -1】
        ret[0] = h;
        h = nums.length;
//按此时寻找右边界 当让h始终是右边界值右边的那个值 比如 888899 h最后就收敛到9
//l每次会增大 从左边界不断增长到右边界再到右边界右边的值 8-8-8-8-9 结束
        while(l < h){
            int m = l + (h - l) / 2;
            if(nums[m] > target)
                h = m;
            else 
                l = m + 1;
        
        }
        ret[1] = l - 1; //取出右边界
        return ret;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值