剑指offer刷题之旋转数组的最小数字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Alicehzj/article/details/82320220

题目描述

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

二分法:

class Solution:
    def minNumberInRotateArray(self, rotateArray):
        alen = len(rotateArray)
        left = 0
        right = alen - 1
        mid = int( ( left + right ) / 2 )
        while True:
            if right - left <= 1 and right >= left:
                break
            if rotateArray[mid] <= rotateArray[right]:
                right = mid
            else:
                left = mid
            mid = int((left + right) / 2)
        return min(rotateArray[right],rotateArray[left])

 普通遍历:

class Solution:

    def minNumberInRotateArray(self, rotateArray):

        # write code here

        = 0

        while i <= len(rotateArray)-1:

            if rotateArray[i] <= rotateArray[i+1]:

                += 1

            else:

                return rotateArray[i+1]

        return 0

猜你喜欢

转载自blog.csdn.net/Alicehzj/article/details/82320220