zoukankan      html  css  js  c++  java
  • 旋转数组的最小数字-顺序查找

    题目描述

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

    解答

    如果数组第一个数比最后一个数小,则表示该数组没有进行旋转,是有序的,第一个元素就是最小的。

    如果数组第一个数比最后一个数大,则表示该数组进行了旋转,从倒叙查,当查到一个元素大于第一个元素的值,则这个元素的后一个元素就是最小的。

    # coding:utf-8
    
    class Solution:
        def minNumberInRotateArray(self, rotateArray):
            # write code here
            if len(rotateArray) == 0:
                return 0
            low = 0
            high = len(rotateArray) - 1
            if rotateArray[low] > rotateArray[high]:
                while rotateArray[low] > rotateArray[high]:
                    high -= 1
                return rotateArray[high+1]
            if rotateArray[low] == rotateArray[high]:
                return rotateArray[low]
            if rotateArray[low] < rotateArray[high]:
                return rotateArray[low]
    
    
    ret = Solution().minNumberInRotateArray([3,4,5,1,2])
    
    print ret

    结束!

  • 相关阅读:
    11.分类与监督学习,朴素贝叶斯分类算法
    9、主成分分析
    7.逻辑回归实践
    8、特征选择
    6.逻辑归回
    5.线性回归算法
    6.10第十四次作业
    6.2第十三次作业
    5.27第十二次作业
    5.20第十一次作业
  • 原文地址:https://www.cnblogs.com/aaronthon/p/13729601.html
Copyright © 2011-2022 走看看