81. Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
1 bool search(vector<int>& nums, int target) 2 { 3 int first = 0; 4 int last = nums.size(); 5 6 while (first != last) 7 { 8 const int mid = first + (last - first) / 2; 9 10 if (nums[mid] == target) 11 { 12 return true; 13 } 14 15 if (nums[first] < nums[mid]) // 此时一定在递增序列中 16 { 17 if (nums[first] <= target && target < nums[mid]) 18 { 19 last = mid; 20 } 21 else 22 { 23 first = mid + 1; 24 } 25 } 26 else if (nums[first] > nums[mid]) // 此时一定在递增序列中 27 { 28 if (nums[mid] < target && target <= nums[last - 1]) 29 { 30 first = mid + 1; 31 } 32 else 33 { 34 last = mid; 35 } 36 } 37 else // 不一定在递增序列中 ++后再判断 38 { 39 ++first; 40 } 41 } 42 43 return false; 44 }