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].
public class Solution {
    public int[] searchRange(int[] nums, int target) {
        if(nums==null || nums.length==0){
            return null;
        }
        int[] res={-1, -1};
        int len=nums.length;
        
        int low=0;
        int high=len-1;
        int pos=0;
        while(low<=high){
            int mid=low+(high-low)/2;
            pos=mid;
            if(nums[mid]>target){
                high=mid-1;
            }
            else if(nums[mid]< target){
                low=mid+1;
            }
            else{
                res[0]=pos;
                res[1]=pos;
                break;
            }
        }
        if(nums[pos]!=target){
            return res;
        }
        //find the right boundary
        int newLow=pos;
        int newHigh=len-1;
        while(newLow<=newHigh){
            int newMid=newLow+(newHigh-newLow)/2;
            if(nums[newMid]==target){
                newLow=newMid+1;
            }
            else{
                newHigh=newMid-1;
            }
        }
        res[1]=newHigh;
        //find the left boundary
        newLow=0;
        newHigh=pos;
        while(newLow <= newHigh){
            int newMid=newLow+(newHigh-newLow)/2;
            if(nums[newMid] == target){
                newHigh=newMid-1;
            }
            else{
                newLow=newMid+1;
            }
        }
        res[0]=newLow;
        return res;
    }
}

优质内容筛选与推荐>>
1、Chapter1 绪论
2、vue 指令详情及操作
3、新浪校园招聘2013.10.30浙大玉泉4教301笔试的前端妹纸,像雾像雨又像风
4、.net开发微信公众号(1)-启用开发者中心
5、Java面向对象之多态(成员访问特点) 入门实例


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn