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]
.
Summary: Just a practice of binary search.
1 vector<int> searchRange(int A[], int n, int target) { 2 vector<int> range(2,-1); 3 int start = 0; 4 int end = n - 1; 5 while(start <= end) { 6 int median = start + (end - start + 1) / 2; 7 if(A[median] > target) { 8 end = median - 1; 9 }else if (A[median] < target) { 10 start = median + 1; 11 }else { //equals 12 //go right 13 int i = median + 1; 14 for(; i <= end; i ++) { 15 if(A[i] != target){ 16 range[1] = i - 1; 17 break; 18 } 19 } 20 if(range[1] == -1) 21 range[1] = i - 1; 22 //go left 23 i = median - 1; 24 for(; i >= start; i --) { 25 if(A[i] != target){ 26 range[0] = i + 1; 27 break; 28 } 29 } 30 if(range[0] == -1) 31 range[0] = i + 1; 32 33 break; 34 } 35 } 36 return range; 37 }