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]
.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int[] searchRange(int[] A, int target) { 3 int leftBound =-1; 4 int rightBound =-1; 5 int len = A.length; 6 int start = 0; 7 int end = len -1; 8 while(start<=end){ 9 int mid = (start+end)/2; 10 if(target == A[mid]){ 11 leftBound =mid; 12 } 13 if(target<=A[mid]){ 14 end = mid-1; 15 } 16 else{ 17 start = mid+1; 18 } 19 } 20 if(leftBound==-1) return new int[]{leftBound,rightBound}; 21 start = leftBound;end=len-1; 22 while(start<=end){ 23 int mid = (start+end)/2; 24 if(target == A[mid]){ 25 rightBound =mid; 26 } 27 if(target>=A[mid]){ 28 start = mid+1; 29 } 30 else{ 31 end = mid-1; 32 } 33 } 34 return new int[]{leftBound,rightBound}; 35 } 36 }