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]
.
public class Solution { public int[] searchRange(int[] A, int target) { int [] result = {-1,-1}; if (A.length == 0) return result; int low = 0 ; int high = A.length-1; int mid = 0; while(low <= high){ mid = (low + high)/2; if (A[mid]<target) low = mid +1; else if (A[mid]>target) high = mid -1; else{ result[0] = mid; result[1] = mid; break; } } low= mid ; while(low >=0 &&A[low]==target){ result[0]= low; low--; } high = mid; while(high <A.length && A[high]==target){ result[1]= high; high++; } return result; } }