Follow to "Search in rotated Sorted Array":
What if duplicates is allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given the target was in the array.
Analysis: When a repeating element is allowed to appear, then the sequence that the search in rotated Sorted array Line14:nums[low] <= nums[mid) can determine is not a monotonically increasing sequence, for example [3,1,3,3,3]. In this case, you simply split the original condition into two scenarios:
1. Nums[low] < Nums[mid] Then the sequence must be incremented, the code is in the search in rotated Sorted array line14~17
2. Nums[low] = = Nums[mid] because it is not able to determine where the number is increased, reduced, after low++ observation. Because low++ after the Nums[low] will be larger or remain unchanged, become larger to meet Nums[low] > Nums[mid], the same will indicate that has entered the repeating number area.
Run Time 11ms
1 classSolution {2 Public:3 BOOLSearch (vector<int>& Nums,inttarget) {4 if(nums.size () = =0)return false;5 if(nums.size () = =1){6 if(nums[0] = = target)return true;7 Else return false;8 }9 Ten intLow =0, high = Nums.size ()-1; One while(Low <=High ) { A intMid = (low + high)/2; - if(Nums[mid] = = target)return true; - if(Nums[low] <Nums[mid]) { the if(Nums[low] <= target && target < Nums[mid]) high = mid-1; - ElseLow = mid +1; - } - Else if(Nums[low] >Nums[mid]) { + if(Nums[mid] < target && target <= nums[high]) Low = mid +1; - ElseHigh = mid-1; + } A Elselow++; at } - return false; - } -};
Search in rotated Sorted Array II