Problem:
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.
My Analysis:
The idea behind binary search was beautiful and elegenat:we only search for the possible result in the possible part.
If We stick to this principle, we would finally end-in-finding out of the right result.
for this question, even the sorted array is rotated, but we could use extra checking to guarantee we still iterate on The right partion of the array.
1. We firstly find out the mid element in which partion.
(either left or right partion is perfectly ordered)
A. The perfectly ordered partion.
B. The mixed partion.
2. We decision on iterating which part based on the comparsion in the sorted partion. We don't make th could e decsion based on the mixed partion, because we does not know the boundary.
A. IFF the target is in the ordered partion, we search for the target in it.
B. Otherwise, we search the target in other partion. (which means the target must in this partion)
Note The checking condition is "if (A[low] <= A[mid])", rather than "if (A[low] < A[mid])"
Cause we should treat a[low] = A[mid] As the left partion sorted!!!
My Solution:
Public classSolution { Public intSearchint[] A,inttarget) { if(A.length = = 0) return-1; intLow = 0; intHigh = A.length-1; intMID =-1; while(Low <=High ) {Mid= (low + high)/2; if(A[mid] = =target)returnmid; if(A[low] <= A[mid]) {//either left partion or right partion is perfectly sorted. if(A[low] <= target && Target <A[mid]) high= Mid-1; Else Low= Mid + 1; } Else{ if(A[mid] < target && Target <=A[high]) Low= Mid + 1; Else High= Mid-1; } } return-1; }}
[Leetcode#33] Search in rotated Sorted Array