首页 > 代码库 > 34. Search for a Range

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

 

Show Company Tags
Show Tags
Show Similar Problems
 

 

思路:两个bianry search找左右边界。左边界if(nums[mid]==target),继续搜索左边high=mid;右边界nums[mid]==target,继续搜索右边,low=mid.提交后运行结果是个死循环,22的情况就会一直死循环。参考了discussion的一种方法,mid=low+(high-low+1)/2,biase to right.这样结果就没问题了

ref:https://discuss.leetcode.com/topic/59880/one-solution-one-is-two-binary-search-the-other-worst-case-o-n

public class Solution {    public int[] searchRange(int[] nums, int target) {        int l1=0;        int h1=nums.length-1;        int[] res={-1,-1};        while(l1<h1)        {            int mid=l1+(h1-l1)/2;            if(nums[mid]>=target)            {                h1=mid;            }            else            {                l1=mid+1;            }        }        int l2=0;        int h2=nums.length-1;        while(l2<h2)        {            int mid=l2+(h2-l2+1)/2;            if(nums[mid]<=target)            {                l2=mid;            }            else            {                h2=mid-1;            }        }        if(l1<=l2&&nums[l1]==target)        {            res[0]=l1;            res[1]=l2;        }        return res;    }}

 

34. Search for a Range