Search for a Range

Problem:

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].

1. 使用二分查找定位一个target的索引;2. 以该索引为中心,使用二分查找确定范围的左边界和右边界。
Solution:
public class Solution {
    public int[] searchRange(int[] A, int target) {
        if(A==null)
             return new int[]{-1,-1};
        int l = 0,r = A.length-1,m;
        while(l<=r)
        {
             m = (l+r)/2;
             if(target<A[m])
                 r = m - 1;
             else if(target>A[m])
                 l = m + 1;
             else {
                 int mt = m, mm;
                 while(mt<r-1)
                 {
                    mm = (mt+r)/2;
                     if(A[mm]>target)
                         r = mm;
                    else 
                        mt = mm;
                }
                if(A[r]>target)
                    r--;
                mt = m;
                 while(l<mt-1)
                {
                    mm = (l+mt)/2;
                    if(A[mm]<target)
                        l = mm;
                    else 
                        mt = mm;
                }
                 if(A[l]<target)
                    l++;
                return new int[]{l,r};
            }
        }
        return new int[]{-1,-1};
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值