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.
這道題讓在旋轉陣列中搜尋一個給定值,若存在返回座標,若不存在返回-1。我們還是考慮二分搜尋法,但是這道題的難點在於我們不知道原陣列在哪旋轉了,我們還是用題目中給的例子來分析,對於陣列[0 1 2 4 5 6 7] 共有下列七種旋轉方法:
0 1 2 4 5 6 7
7 0 1 2 4 5 6
6 7 0 1 2 4 5
5 6 7 0 1 2 4
4 5 6 7 0 1 2
2 4 5 6 7 0 1
1 2 4 5 6 7 0
二分搜尋法的關鍵在於獲得了中間數後,判斷下面要搜尋左半段還是右半段,我們觀察上面紅色的數字都是升序的,由此我們可以觀察出規律,如果中間的數小於最右邊的數,則右半段是有序的,若中間數大於最右邊數,則左半段是有序的,我們只要在有序的半段裡用首尾兩個陣列來判斷目標值是否在這一區域內,這樣就可以確定保留哪半邊了,程式碼如下:
class Solution { public: int search(vector<int>& nums, int target) { int left = 0, right = nums.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < nums[right]) { if (nums[mid] < target && nums[right] >= target) left = mid + 1; else right = mid - 1; } else { if (nums[left] <= target && nums[mid] > target) right = mid - 1; else left = mid + 1; } } return -1; } };
類似題目:
Search in Rotated Sorted Array II
Find Minimum in Rotated Sorted Array
參考資料:
https://leetcode.com/problems/search-in-rotated-sorted-array/description/
https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14436/Revised-Binary-Search