LeetCode——Search for a Range

题目描述:
Given an array of integers sorted in ascending order, 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].

题目分析:
是Search Insert Position的变形,就是找边界情况。
一共做三次binary search. 第一次试着找target, 若是找到了就存index在res 中, index对应的是边界还是中间的target 不重要。若是找不到直接返回res.
第二次找左边界,在 l = 0 和 target index 中间找,若是取得mid 位置上不等于target 说明左边界应该在后半部分找,若是等于target说明左边界应该在前半部找。
第三次找右边界,道理同上.

代码:

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int [] res = {-1,-1};
        if(nums == null || nums.length == 0){
            return res;
        }
        //find target index
        int l = 0;
        int r = nums.length-1;
        while(l<=r){
            int mid = l+(r-l)/2;
            if(nums[mid] == target){
                res[0] = mid;
                res[1] = mid;
                break;
            }else if (nums[mid] > target){
                r = mid-1;
            }else{
                l = mid+1;
            }
        }
        //if can't find target
        if(res[0] == -1){
            return res;
        }
        l = 0;
        r = nums.length -1;
        int pos = res[0];
        //find the left bound
        while(l<=pos){
            int mid = l+(pos-l)/2;
            if(nums[mid] == target){
                pos = mid-1;
            }else{
                l = mid+1;
            }
        }
        res[0] = l;

        //find the right bound
        pos = res[1];
        while(pos<=r){
            int mid = pos + (r-pos)/2;
            if(nums[mid] == target){
                pos = mid+1;
            }else{
                r = mid-1;
            }
        }
        res[1] = r;
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值