The sword refers to the offer - the minimum number of the rotation array

Moving the first elements of an array to the end of the array is called the rotation of the array. Input a rotation of a non-decreasingly sorted array, output the smallest element of the rotated array. For example, the array {3,4,5,1,2} is a rotation of {1,2,3,4,5}, and the minimum value of the array is 1. NOTE: All elements given are greater than 0, if the array size is 0, please return 0.

To put it bluntly, it is to find the minimum value in the array, but if you write it like the first one below, although the function can be achieved, you will definitely not get the offer when you tear the code on the spot.

class Solution:
    def minNumberInRotateArray(self, rotateArray):
        # write code here
        if not rotateArray:
            return 0
        else:
            return min(rotateArray)
class Solution:
     def minNumberInRotateArray(self, rotateArray):
         # write code here 
        ''' Consider three cases:
        1. The array is an empty array, and the specified return value is 0.
        2. There is only one element in the array, so there is no need to do any comparison, at this time the minimum value is the element
        3. When there are more than one element in the array ''' 
        if (rotateArray== []): 
             return 0
        i = 0
         if (i==len(rotateArray)-1 ):
             return rotateArray[0]
         ''' Considering that the array itself is non-decreasing, it is conceivable that the rotation array contains two sub-arrays, and the sub-arrays themselves are ordered , just convert the two elements of the vector
        Compare between, if the former is greater than the latter, then it can be seen that this is the dividing point between two subarrays, such as [3,4,5,1,2], which contains two ordered subarrays [3,4,5]
        And [1,2], the sub-array itself is non-decreasing, then finding the turning point is the smallest element in the array ''' 
        while (i<len(rotateArray)-1 ):
             if (rotateArray[i]<=rotateArray[i+ 1 ]):
                i+=1
            else:
                return rotateArray[i+1]

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324400866&siteId=291194637