[leetcode] Search for a Range
Search for a Range
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
return
Given
[5, 7, 7, 8, 8, 10]
and target value 8,return
[3, 4]
.分析:二分查找
1 class Solution 2 { 3 public: 4 void Searching(vector<int> &ret, int A[], int s, int e, int target) 5 { 6 if(s > e) 7 { 8 ret.push_back(-1); 9 ret.push_back(-1); 10 return; 11 } 12 13 int mid = (s+e)/2; 14 if(A[mid] < target) 15 Searching(ret, A, mid+1, e, target); 16 else if(A[mid] > target) 17 Searching(ret, A, s, mid-1, target); 18 else 19 { 20 int i = mid - 1; 21 while(i >= s && A[i] == A[mid]) i--; 22 ret.push_back(i + 1); 23 24 i = mid + 1; 25 while(i <= e && A[i] == A[mid]) i++; 26 ret.push_back(i - 1); 27 } 28 } 29 vector<int> searchRange(int A[], int n, int target) 30 { 31 vector<int> ret; 32 if(target < A[0] || target > A[n-1]) 33 { 34 ret.push_back(-1); 35 ret.push_back(-1); 36 } 37 else 38 Searching(ret, A, 0, n-1, target); 39 40 return ret; 41 } 42 };