《劍指offer》之旋轉數組的最小數字(python實現)

 

問題描述:

        把一個數組最開始的若干個元素搬到數組的末尾,我們稱之爲數組的旋轉。 輸入一個非減排序的數組的一個旋轉,輸出旋轉數組的最小元素。 例如數組{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
        length = len(rotateArray)
        if length == 0:
            return 0
        if length == 1:
            return rotateArray[0]
        if length > 1:
            for i in range(length - 1):
                if rotateArray[i] > rotateArray[i+1]:
                    if rotateArray[0] > rotateArray[i+1]:
                        return rotateArray[i+1]
                    else:
                        return rotateArray[0]

二 二分查找方法:

# -*- coding:utf-8 -*-
class Solution:
    def minNumberInRotateArray(self, rotateArray):
        # write code here
        length = len(rotateArray)
        if length == 0:
            return 0
        if length == 1:
            return rotateArray[0]
        if length > 1:
            left = 0
            right = length-1
            while left < right:
                medium = (left + right)/2
                if rotateArray[medium] < rotateArray[right]:
                    right = medium
                else:
                    left = medium+1
            return rotateArray[left]

 

三 使用python 的sort進行排序後輸出最小數:

# -*- coding:utf-8 -*-
class Solution:
    def minNumberInRotateArray(self, rotateArray):
        # write code here
        if rotateArray == []:
            return 0
        if rotateArray != []:
            rotateArray.sort()
            return rotateArray[0]

當然還有一種賊簡便的方法 min(rotateArray)進行輸出,這是利用了min函數,不過這種方法雖簡單但不是面試官想要的答案......

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章