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 is in the order of O(log n).
If the target is not a found in the array, return [-1, -1] .
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
Return [3, 4] .
Due to O (logn) time requirements, it is obvious to find with two points.
The idea is to use a binary search to find one of the target, not found then return [-1,-1]
After finding it, the two-point search is extended from this position to both sides recursively.
Part of the reference to the idea of xiao.he.587.
classSolution { Public: Vector<int> Searchrange (intA[],intNinttarget) {Vector<int> Ret (2, -1); intIND = Helper (A,0, N-1, Target); if(Ind! =-1) {//Find one target intleft =IND; intright =IND; ret[0] =Left ; ret[1] =Right ; //recursively extend left towards 0 while(left = Helper (A,0, left-1, target))! =-1) ret[0] =Left ; //recursively extend right towards n-1 while(right = Helper (A, right+1, N-1, target))! =-1) ret[1] =Right ; } returnret; } intHelper (intA[],intLowintHighinttarget) {//binary Search while(Low <=High ) { intMID = low + (high-low)/2; if(A[mid] = =target)returnmid; Else if(A[mid] >target) high= mid-1; Else Low= mid+1; } return-1; }};
"Leetcode" Search for a Range