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 [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
这道题可以先用二分查找找到target所在的位置location, 然后以location为中心向左右两边扩展,直到值与target不同为止。但这种方法最坏情况的复杂度是O(n),我们可以考虑数组中全是相同元素的情况。奇怪的是代码还是被accepted。此处binary search用迭代法实现:
1 class Solution { 2 public: 3 vector<int> searchRange(int A[], int n, int target) { 4 vector<int> result; 5 6 int l = 0, r = n-1; 7 while(l <= r){ 8 int mid = (l + r)/2; 9 if(target == A[mid]){ 10 int low = mid, high = mid; 11 while(low >= 0 && A[low] == target) 12 low--; 13 while(high < n && A[high] == target) 14 high++; 15 result.push_back(low+1); 16 result.push_back(high-1); 17 return result; 18 }else if(A[mid] < target){ 19 l = mid + 1; 20 }else{ 21 r = mid - 1; 22 } 23 } 24 25 return vector<int>(2,-1); 26 } 27 };
浙公网安备 33010602011771号