title :
follow to "Find Minimum in rotated Sorted Array":
What if duplicates is allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated on some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 ).
Find the minimum element.
The array may contain duplicates.
code : OJ Test via runtime:82 ms
1 classSolution:2 #@param num, a list of integers3 #@return An integer4 deffindmin (self, num):5 #None case6 ifNum isNone:7 returnNone8 #Only one element case9 ifLen (num) ==1 :Ten returnNum[0] One #Binary Search case AStart =0 -end = Len (num)-1 - whileStart<end andnum[start]>=Num[end]: theMid = (start+end)/2 - ifNum[start]>Num[end]: - ifNum[mid]>Num[end]: -Start = Mid+1 + Else: -End =Mid + Else: A ifNum[mid]>Num[end]: atStart = Mid+1 - Else : -Start = Start+1 - returnNum[start]
Ideas :
Compare previous questions: http://www.cnblogs.com/xbf9xbf/p/4261334.html
This problem needs to be considered duplicate case.
To be brief, the core difference compared to the case without duplicate is:
Case:num[start]>num[end without duplicate] is a set-up
Case:num[start]>num[end with duplicate] is not necessarily set up, or may be num[start]==num[end]
is the possibility of such an equal sign, so the most intuitive way is to separate the situation of the equal sign to come out.
There are, therefore, two kinds of situations to be discussed:
1. Num[start]>num[end]
2. Num[start]==num[end]
One might ask, "Why can't there Be a num[start]<num[end" situation? A: Since the num[start]>=num[end]; is already qualified in the while loop termination condition, the current start-to-end array is already ordered, and return directly [Start] is OK.
Tips:
There are several issues before AC:
1. If there is no way to determine whether the minimum is in the left or right half of the time, do not start=start+1 end=end-1,start=start+1 at the same time, otherwise the pointer overflow
2. Before the while loop condition, the Start<=end is always written. is more such an equal sign, submit a few times has been unable to AC. The reason, if start==end, will cause the execution of start=start+1 statements, either overflow or wrong. If you modify the condition of the while loop, Start<end, then automatically exits the loop when Start==end, and returns Num[start].
Leetcode "Find Minimum in rotated Sorted Array II" Python implementation