Search for a Range
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Search for a Range相关的知识,希望对你有一定的参考价值。
Given a sorted array of n integers, find the starting and ending position of a given target value.
If the target is not found in the array, return [-1, -1]
.
Example
Given [5, 7, 7, 8, 8, 10]
and target value 8
,
return [3, 4]
.
Challenge
O(log n) time.
Binary Search
public class Solution { /** *@param A : an integer sorted array *@param target : an integer to be inserted *return : a list of length 2, [index1, index2] */ public int[] searchRange(int[] A, int target) { // write your code here int[] res=new int[]{-1,-1}; if(A==null || A.length==0||A[0]>target ||A[A.length-1]<target) return res; int begin=0; int end=A.length-1;while(begin<=end) { int mid=(begin+end)/2; if(A[mid]<target) { begin=mid+1; } else if(A[mid]>target) { end=mid-1; } else { begin=mid; end=mid; while(begin>=0 && A[begin]==target) { begin--; } res[0]=begin+1; while(end<A.length && A[end]==target) { end++; } res[1]=end-1; break; } } return res; } }
以上是关于Search for a Range的主要内容,如果未能解决你的问题,请参考以下文章