Actually, we are searching the right end of the target so:
1. start could be same as end
2. A[mid] > target, shift to left
3. A[mid] <= target shift to right
1 class Solution { 2 public: 3 int bsearch(int A[], int start, int end, int target) { 4 int index = -1, mid = 0; 5 while (start <= end) { 6 mid = (start + end)/2; 7 if (A[mid] <= target) { 8 start = mid + 1; 9 index = mid; 10 } else { 11 end = mid - 1; 12 } 13 } 14 return index; 15 } 16 vector<int> searchRange(int A[], int n, int target) { 17 vector<int> result(2, -1); 18 result[0] = bsearch(A, 0, n-1, target-1) + 1; 19 result[1] = bsearch(A, 0, n-1, target); 20 if (result[0] == -1 || A[result[0]] != target) { 21 return vector<int> (2, -1); 22 } 23 return result; 24 } 25 };