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]
.
Ideas:
1. In fact, if target value duplicated, find the duplicated range
Two points to find target, left and right to search index up and down bounds; no, return [ -1,-1]
2. In the standard binary search modify, first find left one;
Comparison: The worst case scenario for Method 1 is that O (n): [1,1,1,1,1,1] Find 1; Normally O (lgn+r)
The worst case scenario for Method 2 is that target is only appear once; the worst is the best of O (2LGN); You can increase your judgment to improve the condition of only once to O (LGN);
classSolution { Public: Vector<int> Searchrange (intA[],intNinttarget) { intlow=0; inthi=n-1; intMid=0; intindex; Vector<int>range; while(low<=hi) {Mid= (Low+hi)/2; if(Target==a[mid]) {index=mid; Break;} if(Target<a[mid]) hi=mid-1; ElseLow=mid+1; } if(hi<Low ) {Range.push_back (-1); Range.push_back (-1); returnrange; } intindexlow=index; intIndexhi=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); returnrange; }};
Search for a Range