Search for the rotated array. Scanning from the beginning, the complexity of O (N) can also pass, or even sort the following first, and then perform the second. However, the purpose of this question is certainly not here.
Think about the impact of rotation on our search. If it has not been rotated, We will directly compare the size of the target and A [middle], and then we will always be very sure to lose half of the source array, that is, we will cut the search space by half, but after rotation, only A [middle] cannot determine the next round, because even if A [middle] is larger than target, we should look forward, however, if the source array is shifted to the left loop, a smaller number may be in the second half.
The above is the difference between rotation and non-rotation. This is easy to understand. The key is that there is no change after rotation? The answer is that no matter how it is rotated, at least one of the left and right parts of the middle must be completely ordered. This should be easy to understand. It is easy to determine which half is. Just check the size relationship between A [middle] And A [0] And A [N. If it is ordered, we can compare the size of the endpoint and target to determine that the target should not be in this part. If it is not there, we will recursively query the other half. Based on this policy, we can lose half of the time that is determined each time, and the time complexity will decrease.
Do not forget that this question has a strong assumption that there are no repeated elements in the array. The elements with repeated elements are very different. It is the content of the next question.
int msearch(int A[], int n, int target, int* a){ if(n<=0) return -1; int middle = n/2; if(A[middle] == target) return A-a+middle; if(A[middle]>target){ if(A[0]<=target||A[0]>A[middle]){ return msearch(A, middle, target, a); }else{ return msearch(A+middle+1, n-middle-1, target, a); } }else{ if(A[0]<=A[middle]||A[n-1]>=target) return msearch(A+middle+1, n-middle-1, target, a); else{ return msearch(A, middle, target, a); } }}class Solution {public: int search(int A[], int n, int target) { return msearch(A, n, target, A); }};