(i.e., 0 1 2 4 5 6 7 might become 4 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.
Idea: We need a more careful binary search in this problem. When we split the array to two halves, there must be at least one half is normal (ascending order). We compare the head and the tail of this normal half with the target, if the target is in this normal half, then binary search in this half, otherwise search the other half. The other half may be rotated or not, but it does not matter, since it is mathematically the same as the original array (an array with at most one pivot).
Time: O(lgn) Space: O(1)
Code:
public class Solution {
public int search(int[] A, int target) {
int left=0;
int right=A.length-1;
while(left<=right)
{
int mid=(left+right)/2;
if(A[mid]==target)
return mid;
if(A[left]<=A[mid])
{
if(target<A[mid]&&target>=A[left])
right=mid-1;
else
left=mid+1;
}
else
{
if(target<=A[right]&&target>A[mid])
left=mid+1;
else
right=mid-1;
}
}
return -1;
}
}
No comments:
Post a Comment