Search in rotated Sorted Array
Suppose a sorted array is rotated on some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
You is given a target value to search. If found in the array is return its index, otherwise return-1.
Assume no duplicate exists in the array.
Solution 1:
Use the nine-chapter algorithm for classic recursive templates:
while (L < r-1) You can avoid the mid-to-left overlap phenomenon.
In fact, and the general dichotomy search is not much different.
The problem is that every time we want to find the normal sort of part, you just need to compare mid, left, if they are positive, it means
Normal sorting, and the right side is disconnected, that is, because the rotated occurred in abnormal sequence.
For example:
4567012 if we take mid to 7, then the left side is the normal sequence, and the right 7012 is not normal.
Then we compare the target with the normal sort side, if Target is on the left, discard the right, and vice versa, discard
Left. Once we can throw half. As fast as a two-point search.
1 Public classSolution {2 Public intSearchint[] A,inttarget) {3 if(A = =NULL|| A.length = = 0) {4 return-1;5 }6 7 intL = 0;8 intr = A.length-1;9 Ten while(L < R-1) { One intMID = L + (r-l)/2; A - if(A[mid] = =target) { - returnmid; the } - - //Left side is sorted. - //BUG 1:if don ' t use >=, and use L < R in while loop, than there is some problem. + if(A[mid] >A[l]) { - if(Target > A[mid] | | Target <A[l]) { + //move to right; AL = Mid + 1; at}Else { -r = Mid-1; - } -}Else { - if(Target < A[mid] | | target >A[r]) { - //move to left; inr = Mid-1; -}Else { toL = Mid + 1; + } - } the } * $ if(A[l] = =target) {Panax Notoginseng returnl; -}Else if(A[r] = =target) { the returnR; + } A the return-1; + } -}
View CodeSolution 2:
Note that if the while loop uses L <= r to card, then mid is likely to come up to L, so when judging whether it is ordered, we must use <=
In short, this code does not need to judge the value of L,r at last.
1 Public intSearchint[] A,inttarget) {2 if(A = =NULL|| A.length = = 0) {3 return-1;4 }5 6 intL = 0;7 intr = A.length-1;8 9 while(L <=r) {Ten intMID = L + (r-l)/2; One A if(A[mid] = =target) { - returnmid; - } the - //Left side is sorted. - //BUG 1:if don ' t use >=, and use L < R in while loop, than there is some problem. - if(A[mid] >=A[l]) { + if(Target > A[mid] | | Target <A[l]) { - //move to right; +L = Mid + 1; A}Else { atr = Mid-1; - } -}Else { - if(Target < A[mid] | | target >A[r]) { - //move to left; -r = Mid-1; in}Else { -L = Mid + 1; to } + } - } the * return-1; $}
View Code
Followup:leetcode new topic: Find Minimum in rotated Sorted Array problem solving ... Leetcode new topic: Find Minimum in rotated Sorted Array II solution ...
Code: GitHub Code Link
Leetcode:search in rotated Sorted Array problem Solving report