Suppose a sorted array is rotated at some unknown to you beforehand.
(I. e .,0 1 2 4 5 6 7Might become4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return-1.
You may assume no duplicate exists in the array.
Problem: Find the target using the binary method.
- If a [l] <A [Mid], it indicates that the mid is left ordered and smaller than the mid, as shown in. In this case, if the target is between the L and mid, you need to reset R to mid. In other cases, you need to continue searching on the right end of mid.
2. if a [l]> = A [Mid], the mid is in the right order and all are greater than the mid, as shown in. If the target is between the mid and the R, then you need to reset L to mid. In other cases, you need to continue searching on the left end of mid.
When l + 1 = r, you only need to check whether the elements pointed to by L and R are equal to the target.
The Code is as follows:
1 public class Solution { 2 public int search(int[] A, int target) { 3 int l = 0; 4 int r = A.length - 1; 5 6 while(l + 1< r){ 7 int mid = l + (r-l)/2; 8 if(A[mid] == target) 9 return mid;10 if(A[l]< A[mid] ){11 if(A[mid] >= target && A[l] <= target)12 r = mid;13 else {14 l = mid;15 }16 }17 else {18 if(target >= A[mid] && target <= A[r])19 l = mid;20 else {21 r = mid;22 }23 }24 }25 26 if(target == A[l])27 return l;28 if(target == A[r])29 return r;30 return -1;31 }32 }