首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。