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?
1 class Solution { 2 public: 3 bool search(vector<int>& nums, int target) { 4 if (nums.empty())return false; 5 int pivot = nums[0], n = nums.size(), s = 0, e = n - 1; 6 while (e>=s && nums[e] == pivot) 7 e--; 8 if (e < s)return pivot == target; 9 while (s <= e) { 10 int mid = (s + e) / 2; 11 if (nums[mid] >= pivot) 12 s = mid + 1; 13 else 14 e = mid - 1; 15 } 16 int mididx = e, S, E; 17 if (pivot > target) 18 S = mididx + 1, E = n - 1; 19 else 20 S = 0, E = mididx; 21 while (S <= E) { 22 int mid = (S + E) / 2; 23 if (nums[mid] < target) 24 S = mid + 1; 25 else if (nums[mid] == target)return true; 26 else E = mid - 1; 27 } 28 return false; 29 } 30 };