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].
Solution: It takes O(lgN) to find both the lower-bound and upper-bound.
1 class Solution { 2 public: 3 int lowerBound(int A[], int n, int target) { 4 int i = 0, j = n-1; 5 while(i <= j) { 6 int mid = i + (j-i)/2; 7 if(A[mid] < target) 8 i = mid+1; 9 else 10 j = mid-1; 11 } 12 if(i == -1 || i == n || A[i] != target) return -1; 13 else return i; 14 } 15 16 int upperBound(int A[], int n, int target) { 17 int i = 0, j = n-1; 18 while(i <= j) { 19 int mid = i + (j-i)/2; 20 if(A[mid] <= target) { 21 i = mid+1; 22 } 23 else { 24 j = mid-1; 25 } 26 } 27 if(j == -1 || j == n || A[j] != target) return -1; 28 else return j; 29 } 30 31 vector<int> searchRange(int A[], int n, int target) { 32 vector<int> res(2,-1); 33 res[0] = lowerBound(A, n, target); 34 res[1] = upperBound(A, n, target); 35 return res; 36 } 37 };