Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6]
might become [2,5,6,0,0,1,2]
).
You are given a target value to search. If found in the array return true
, otherwise return false
.
Example 1:
Input: nums = [2,5,6,0,0,1,2]
, target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2]
, target = 3
Output: false
Follow up:
- This is a follow up problem to Search in Rotated Sorted Array, where
nums
may contain duplicates. - Would this affect the run-time complexity? How and why?
這道是之前那道 Search in Rotated Sorted Array 的延伸,現在數組中允許出現重復數字,這個也會影響我們選擇哪半邊繼續搜索,由於之前那道題不存在相同值,我們在比較中間值和最右值時就完全符合之前所說的規律:如果中間的數小於最右邊的數,則右半段是有序的,若中間數大於最右邊數,則左半段是有序的。而如果可以有重復值,就會出現來面兩種情況,[3 1 1] 和 [1 1 3 1],對於這兩種情況中間值等於最右值時,目標值3既可以在左邊又可以在右邊,那怎么辦么,對於這種情況其實處理非常簡單,只要把最右值向左一位即可繼續循環,如果還相同則繼續移,直到移到不同值為止,然后其他部分還采用 Search in Rotated Sorted Array 中的方法,可以得到代碼如下:
class Solution { public: bool search(vector<int>& nums, int target) { int n = nums.size(), left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] == target) return true; if (nums[mid] < nums[right]) { if (nums[mid] < target && nums[right] >= target) left = mid + 1; else right = mid - 1; } else if (nums[mid] > nums[right]){ if (nums[left] <= target && nums[mid] > target) right = mid - 1; else left = mid + 1; } else --right; } return false; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/81
類似題目:
Search in Rotated Sorted Array
參考資料:
https://leetcode.com/problems/search-in-rotated-sorted-array-ii/