Suppose an array sorted in ascending order is rotated at 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 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.
Solution:Binary Search
Example: [7 8 9 0 1 2 3 4 5 6]
思路: Binary Search 在mid處 二分parts侮叮,若A[lo] <= A[mid]戳晌,則可知左邊正常增序嚎卫,則右邊part含有rotated部分,vice versa氮块。二分確定好parts后庸疾,來判斷target是在哪個part中就可以繼續(xù)二分查找(通過正常這邊的前后范圍判斷狠裹,else則在rotated那邊)。循環(huán)此過程直到在A[mid]找到target或! lo < hi舆床。
Time Complexity: O(logN) Space Complexity: O(1)
Solution Code:
class Solution {
public int search(int[] A, int target) {
if(A == null || A.length == 0) return -1;
int lo = 0, hi = A.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (A[mid] == target) return mid;
if (A[mid] >= A[lo]) {
// rotated part is in the right
if (target >= A[lo] && target < A[mid]) {
// target is in the left
hi = mid - 1;
} else {
// target is in the right
lo = mid + 1;
}
} else {
// rotated part is on the left
if (target > A[mid] && target <= A[hi]) {
// target is in the right
lo = mid + 1;
} else {
// target is in the left
hi = mid - 1;
}
}
}
return -1;
}
}