Wins the offer - to find the minimum number of rotations column

Title Description

The beginning of an array of several elements moved to the end of the array, the array we call rotation.
A non-descending order of the input array of a rotation of the output rotary smallest element array.
For example, an array {3,4,5,1,2} {1,2,3,4,5} is a rotation of the array to a minimum.
NOTE: All the elements are given in greater than 0, if the array size is 0, return 0.

 

violence:

Increasing the number of columns is two sub-sequences, so they find a combination that point just fine.

Start from scratch to find, to find the first value is smaller than mini

class Solution:
    def minNumberInRotateArray(self, rotateArray):
        if len(rotateArray) == 0:
            return 0
        mini = rotateArray[0]
        i = 1
        while i <len(rotateArray):
            if rotateArray[i]<mini:
                return rotateArray[i]
            else:
                i += 1
        return mini

 

Optimization - dichotomy:

# -*- coding:utf-8 -*-
class Solution:
    def minNumberInRotateArray(self, rotateArray):
        if len(rotateArray) == 0:
            return 0
        l = 0
        r = len(rotateArray)-1
        while l < r :
            # 这里注意一下,可能从第0号元素开始旋转,所以可能整个数组递增。
            if rotateArray[l]<rotateArray[r]:
                return rotateArray[l]
            
            # 为了避免死循环 mid = (l+r)//2 和 l = mid+1 搭配
            #              mid = (l+r+1)//2 和 r = mid -1搭配使用
            mid = l + (r-l)//2
            if rotateArray[l]<rotateArray[mid] or rotateArray[r]<rotateArray[mid]:
                l = mid + 1
            elif rotateArray[l]>rotateArray[mid] or rotateArray[r]>rotateArray[mid]:
                r = mid
            else:
                while l<r and rotateArray[l]==rotateArray[mid]:
                    l += 1
        return rotateArray[l]

 

 

Published 45 original articles · won praise 1 · views 3352

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104708669