一、Problem
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.
Your algorithm’s runtime complexity must be in the order of O(log n).
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
二、Solution
方法一:二分
- 樸素的二分搜索要求數組是單調的,而經過旋轉的數組必定具有兩種單調性。所以如何找到單調區間成爲本題重點,本題可劃分爲幾步:
- 先找到一個連續遞增區間。
- 從遞增區間裏面再次確定左右邊界。
邊界錯誤:這裏需要注意的是,當出現等於 = 的情況,我們依舊要把邊界移動,否則,會進入死循環…😂
public int search(int[] A, int t) {
int l = 0, r = A.length-1;
while (l <= r) {
int m = (l + r) >>> 1;
if (A[m] == t)
return m;
if (A[l] <= A[m]) {
if (A[l] <= t && t <= A[m]) r = m - 1;
else l = m + 1;
} else {
if (t >= A[m] && t <= A[r]) l = m + 1;
else r = m;
}
}
return -1;
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,