Suppose a sorted array 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.
利用二分查詢,通過中間元素和左右兩個元素比較,判斷哪一部分有序的
- 如果左半部分有序的,目標值落在有序區間裡,那麼移動右指標,因為無序的部分要麼比中間元素大,要麼比左端元素小,如果目標值不在有序區間內,則移動左指標
- 如果右半部分有序的,目標值落在有序區間裡,那麼移動左指標,拋棄左半部分,如果目標值不在有序區間裡,拋棄右半部分,則移動右指標
class Solution { public: int search(int A[], int n, int target) { int left = 0, right = n-1; while(left <= right){ int mid = left+(right-left)/2; if(A[mid] == target) return mid; if(A[left]<= A[mid]){ if(A[left] <=target && A[mid] > target) right = mid-1; else left = mid+1; }else{ if(A[mid] < target && target <= A[right]) left = mid+1; else right =mid-1; } } return -1; } };
如果陣列中含有相同值的元素,在左端元素、中間元素和右端元素相等的情況下,無法判斷出哪一部分有序。在這種情況下,只能把左指標向前移動一步。
因此、在最壞情況下時間複雜度是O(n)