Get idea from Code Ganker (优快云)′solution
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.
Analysis
The solution is similar to the problem Search in Rotated Sorted (Array. However, the thing would be different if duplicates are allowed. In Search in Rotated Sorted Array, we know which half to choose based on the value of left, mid and right.
But if duplicates are allowed, there are some special cases, like [3,3,3,3,3,1,2], [3,1,2,3,3,3,3]. In these cases, nums[mid]=nums[left]=nums[right], and we are not able to know which half should be chosen. So, the idea is to keep movinng left by 1 until num[left]!=num[mid].
Complexity
if all elements are equal, the running time would be O(n)
Solution
class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {boolean}
def search(self, nums, target):
if len(nums)==0 or target==None:
return False
return self.subsearch(nums,target, 0, len(nums)-1)
def subsearch(self,nums,target,left,right):
mid = (left+right)/2
if nums[mid]==target:
return True
if nums[left]>nums[mid]:
if target>nums[mid] and target<=nums[right]:
left = mid + 1
else:
right = mid - 1
elif nums[left]<nums[mid]:
if nums[left]<=target and target<nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
left = left + 1
if left > right:
return False
else:
return self.subsearch(nums,target,left,right)
the difference is that we add
else:
left = left + 1