[LeetCode]Search in Rotated Sorted Array II

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.

Search in Rotated Sorted Array一样,将return mid改成return true,将return -1改成return false即可。

 1 class Solution {
 2 public:
 3     bool search(vector<int>& nums, int target) {
 4         if(nums.size()==0) return -1;
 5         int left=0,right=nums.size()-1;
 6         while(left<=right)
 7         {
 8             int mid = (left+right)/2;
 9             if(nums[mid]==target) return true;
10             if(nums[mid]>nums[left])
11             {
12                 if(target <= nums[mid] && target >= nums[left]) right = mid - 1;
13                 else left = mid + 1;
14             }
15             else if(nums[mid]<nums[left])
16             {
17                 if(target >= nums[left] || target <= nums[mid]) right = mid -1;
18                 else left = mid + 1;
19             }
20             else left ++;
21         }
22         return false;
23     }
24 };
原文地址:https://www.cnblogs.com/Sean-le/p/4810227.html