Simple algorithmic problem, Find Minimum in rotated Sorted Array python implementation.
Topic:
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.
Assume no duplicate exists in the array.
This is an algorithm problem on Leetcode, test instructions is an already sorted array, truncated and re-stitched to find the smallest number in the array.
It's too easy to use Python for this topic. The code is as follows:
class Solution: # @param num, a list of integers # @return an integer def findmin (self, num): return min (num)
Using the Python built-in min function, passed after submission, time is:runtime:184 ms
After the completion of the Groove: "Are you so interesting?" "Well, that's really boring. Then consider optimizing it.
Python's built-in min function iterates through the entire array, with a time complexity of O (n), but this array would have been ordered, so you can do a little bit of optimization with the code as follows:
class Solution: # @param num, a list of integers # @return an integer def findmin (self, num): for in range (0, Len (num)-1): if(Num[i] > num[i+1]): return num[i+1] return num[0]
When you find a number that is less than the first value, you can end the loop. At this point the code's theoretical complexity is still O (n), but it's actually going to be a little bit faster.
After submission, see test results, Time is:runtime:164 Ms, it seems that the optimization or a little effect, a little bit faster.
Can you get a little faster? The Sorted mentioned in the topic (sorted), it is easy to think of the use of dichotomy to find, but this sort is not the real sort, is truncated, so to do a little bit of work. The code to try to join the binary lookup is as follows:
classSolution:#@param num, a list of integers #@return An integer deffindmin (self, num): I=0 J= Len (num)-1 while(I < J-1): Point= Int ((i + j)/2) if(Num[point] >Num[i]): I= Pointif(Num[point] <Num[j]): J= PointreturnMin (num[0], num[i], num[j])
Using the dichotomy method to approximate the smallest number, the time complexity of the code is O (LOG2N), after submission, look at the test results, time-consuming is:runtime:140 Ms. The effect is OK.
This should be the best result I can do.
Simple algorithmic problem, Find Minimum in rotated Sorted Array python implementation.