二分搜索变种
代码:
1 vector<int> searchRange(int A[], int n, int target) { 2 vector<int> range(2, -1); 3 int l, r; 4 5 // left 6 l = 0; 7 r = n - 1; 8 while (l <= r) { 9 int m = (l + r) / 2; 10 if (A[m] < target) 11 l = m + 1; 12 else 13 r = m - 1; 14 } 15 if (l < n && A[l] == target) 16 range[0] = l; 17 18 // right 19 l = 0; 20 r = n - 1; 21 while (l <= r) { 22 int m = (l + r) / 2; 23 if (A[m] > target) 24 r = m - 1; 25 else 26 l = m + 1; 27 } 28 if (r >= 0 && A[r] == target) 29 range[1] = r; 30 31 return range; 32 }