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