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]
.
思路:
1.其实就是 if target value duplicated, find the duplicated range
二分找到target,左右遍历找index上下界;没找到,就返回[-1,-1]
2. 在标准binary search修改,先找left one;然后找right one。
比较: 方法1的最坏情况是,O(n) :[1,1,1,1,1,1] find 1; 一般情况下是O(lgn+r)
方法2的最坏情况是,target only appear once;最坏最好都是 O(2lgn);可以增加判断,将only once的情况改进成O(lgn);
class Solution { public: vector<int> searchRange(int A[], int n, int target) { int low=0; int hi=n-1; int mid=0; int index; vector<int> range; while(low<=hi){ mid=(low+hi)/2; if(target==A[mid]){ index=mid;break;} if(target<A[mid]) hi=mid-1; else low=mid+1; } if(hi<low) { range.push_back(-1); range.push_back(-1); return range; } int indexLow=index; int indexHi=index; while(indexHi<n-1){ if(A[indexHi]==A[indexHi+1]) indexHi++; else break; } while(indexLow>0){ if(A[indexLow]==A[indexLow-1]) indexLow--; else break; } range.push_back(indexLow); range.push_back(indexHi); return range; } };