码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer 面试11题

时间:2018-06-15 13:16:56      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:number   index   write   array   排序   odi   sel   span   HERE   

面试11题:

题目:

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

解题思路:二分查找,以及分情况考虑(稍显麻烦)详见:剑指offer P83

解题代码:

# -*- coding:utf-8 -*-
class Solution:
    def minNumberInRotateArray(self, rotateArray):
        # write code here
        if not rotateArray:
            return
        if len(rotateArray)==0:
            return 0
        index1=0
        index2=len(rotateArray)-1
        indexMid=index1
        while (rotateArray[index1]>=rotateArray[index2]):
            if (index2-index1)==1:
                indexMid=index2
                break
            indexMid = (index1+index2)//2
            # 如果index1 index2 indexMid三者相等
            if rotateArray[index1]==rotateArray[index2] and rotateArray[indexMid]==rotateArray[index1]:
                return self.minValue(rotateArray,index1,index2)

            if rotateArray[indexMid]>=rotateArray[index1]:
                index1=indexMid
            if rotateArray[indexMid]<=rotateArray[index2]:
                index2=indexMid

        return rotateArray[indexMid]

    def minValue(self,rotateArray,index1,index2):
        res=rotateArray[index1]
        for i in range(index1+1,index2+1):
            if res>rotateArray[i]:
                res=rotateArray[i]
        return res

 

剑指offer 面试11题

标签:number   index   write   array   排序   odi   sel   span   HERE   

原文地址:https://www.cnblogs.com/yanmk/p/9186475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!