劍指offer6:旋轉陣列的最小數字
阿新 • • 發佈:2018-11-27
思路:
1.先判斷陣列的長度是否為0,1。
2.然後從陣列的頭和尾開始遍歷。先算出他們的中間下標mid,將中間元素rotateArray[mid]和尾元素rotateArray[high]比較大小。若中間元素大於尾元素則最小元素一定在中間元素的右邊即low=mid+1。若中間元素小於尾元素則最小元素要不就是中間元素要麼在中間元素右邊即high=mid。若中間元素和尾元素相等則high=high-1。依次迴圈直到結束。
# -*- coding:utf-8 -*- class Solution: def minNumberInRotateArray(self, rotateArray): # write code here if len(rotateArray)==0: return 0 if len(rotateArray)==1: return rotateArray[0] low,high=0,len(rotateArray)-1 while low<=high: mid=(low+high)//2 if rotateArray[mid]>rotateArray[high]: low=mid+1 elif rotateArray[mid]<rotateArray[high]: high=mid else: high-=1 return rotateArray[high]