Https://leetcode.com/problems/search-in-rotated-sorted-array/?tab=Description
Very good, very classic topic. Review it today. Although there are previous ideas, the processing of equal numbers is complex and error-prone. Today, I saw a good solution.
Https://discuss.leetcode.com/topic/3538/concise-o-log-n-binary-search-solution
The idea is to find the smallest number of subscripts, through mid > Hi, on low = mid+1, otherwise hi=mid, to find out.
Then the two points are searched, with the actual subscript offset.
Overall code:
classSolution { Public: intSearchintA[],intNinttarget) { intlo=0, hi=n-1; //find the index of the smallest value using binary search. //Loop would terminate since mid < Hi, and lo or hi'll shrink by at least 1. //Proof by contradiction, so mid < Hi:if Mid==hi, then Lo==hi and Loop would has been terminated. while(lo<hi) { intMid= (Lo+hi)/2; if(A[mid]>a[hi]) lo=mid+1; ElseHi=mid; } //Lo==hi is the index of the smallest value and also the number of places rotated. introt=Lo; Lo=0; hi=n-1; //The usual binary search and accounting for rotation. while(lo<=hi) { intMid= (Lo+hi)/2; intRealmid= (Mid+rot)%N; if(A[realmid]==target)returnRealmid; if(A[realmid]<target) lo=mid+1; Elsehi=mid-1; } return-1; }};
Of course, there is a conventional approach, and that's it.
When considering a problem, don't be too complicated.
Public intSearchint[] A,inttarget) { intLo =0; inthi = A.length-1; while(Lo <hi) { intMid = (lo + hi)/2; if(A[mid] = = target)returnmid; if(A[lo] <=A[mid]) { if(Target >= A[lo] && Target <A[mid]) {Hi= Mid-1; } Else{lo= Mid +1; } } Else { if(Target > A[mid] && target <=A[hi]) {Lo= Mid +1; } Else{Hi= Mid-1; } } } returnA[lo] = = target? Lo:-1;}
Searching for rotated arrays-classic