1 class Solution {
2 /**
3 *@param A : an integer sorted array
4 *@param target : an integer to be inserted
5 *return : a list of length 2, [index1, index2]
6 */
7 public:
8 vector<int> searchRange(vector<int> &A, int target) {
9 // write your code here
10 vector<int> result;
11 int size = A.size()-1;
12 if(A.empty()) {
13 result.push_back(-1);
14 result.push_back(-1);
15 }
16 else {
17 result.push_back(getFirstTarget(A, target, 0, size));
18 result.push_back(getLastTarget(A, target, 0, size));
19 }
20 return result;
21 }
22
23 int getFirstTarget(vector<int> &A, int target, int low, int high) {
24 if(low > high)
25 return -1;
26 int mid = (low+high)/2;
27 if(A[mid] == target) {
28 if((mid>0 && A[mid-1]!=target) || mid==0)
29 return mid;
30 else
31 high = mid-1;
32 }
33 else if(A[mid] > target)
34 high = mid-1;
35 else
36 low = mid+1;
37
38 return getFirstTarget(A, target, low, high);
39 }
40
41 int getLastTarget(vector<int> &A, int target, int low, int high) {
42 int size = A.size()-1;
43 if(low > high)
44 return -1;
45 int mid = (low+high)/2;
46 if(A[mid] == target) {
47 if((mid<size && A[mid+1]!=target) || mid==size)
48 return mid;
49 else
50 low = mid+1;
51 }
52 else if(A[mid] > target)
53 high = mid-1;
54 else
55 low = mid+1;
56
57 return getLastTarget(A, target, low, high);
58 }
59 };