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
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
这种题自我感觉比较难.仍遵循二分查找的整体框架:
以 [4 5 6 7 0 1 2] 为例
while(lo < hi){
case1: A[mid] > A[hi] 这时,看看 ta 在 4...mid 之间吗?
case2: A[mid] < A[hi] 这时,看看 ta 在 mid...2 之间吗?
case3: A[mid] == A[hi] 这时, hi--;
}
人家思想,自个代码:
(O(logn)) time, (O(1)) extra space.
bool search(vector<int>& A, int ta) {
const int n = A.size();
if (n == 0) return false; // special case
int lo = 0, hi = n - 1;
while (lo < hi) {
int mid = lo + ((hi - lo) >> 1);
if (A[mid] == ta) return true;
if (A[mid] > A[hi]) {
if (ta < A[mid] && ta >= A[lo]) hi = mid;
else lo = mid + 1;
} else if (A[mid] < A[hi]) {
if (ta > A[mid] && ta <= A[hi]) lo = mid + 1;
else hi = mid;
} else hi--;
}
return ta == A[lo] ? true : false;
}