https://oj.leetcode.com/problems/search-in-rotated-sorted-array/
A rotated array that requires a binary search query for a number. Modified binary search can be done. Note that a[l]<a[r] can be used to determine the l,r median distribution of numbers. In A[l]>a[r], there is a discontinuity in the middle. The position relationship between the midpoint and the center of rotation can be judged by a[mid]>a[r]. Then move L or R through a logical comparison. Draw a line chart to understand better.
Note that the binary search termination condition is l<r, and the l=mid+1 is always used when updating the L position. This avoids the cycle of death. Determines whether a query is queried after exiting the loop by judging A[l] and the target relationship.
classSolution { Public: intSearchintA[],intNinttarget) { intL=0; intr=n-1; intx=Target; while(r>l) { intMid= (L+R)/2; if(X==a[mid])returnmid; if(a[l]<A[r]) { if(X<a[mid]) r=mid; ElseL=mid+1; } Else{//Al>ar if(a[mid]<A[r]) { if(X<a[mid]) r=mid; Else { if(X>a[r]) r=mid; ElseL=mid+1; } } Else { if(X>a[mid]) l=mid+1; Else { if(X>a[r]) r=mid; ElseL=mid+1; } } } } if(a[l]==x)returnl; return-1; }};
Leetcode-search in rotated Sorted array-rotation array Search-two points search + algebraic logic