知识点:二分查找
思路一:
顺序遍历,当后一个数比前一个数小时,则为最小数
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
for i in range(len(rotateArray)):
if rotateArray[i+1] < rotateArray[i]:
return rotateArray[i+1]
思路二:
投机取巧,直接使用python min函数
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
return min(rotateArray)
思路三:
二分查找
- 找mid = (front + rear)
- if rotateArray[mid] > rotateArray[rear]:说明最小数在后半部分,front = mid;
- if rotateArray[mid] < rotateArray[front]:说明最小数在前半部分,rear = mid;
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
front = 0
rear = len(rotateArray) - 1
if rotateArray[front] < rotateArray[rear]:
return rotateArray[front]
min_val = rotateArray[0]
while (rear - front) > 1:
mid = (rear + front) // 2
if rotateArray[mid] > rotateArray[rear]:
front = mid
elif rotateArray[mid] < rotateArray[front]:
rear = mid
elif rotateArray[front] == rotateArray[mid] and rotateArray[mid] == rotateArray[rear]:
for i in range(1, len(rotateArray)):
if rotateArray[i] < min_val:
rear = i
min_val = rotateArray[i]
return rotateArray[rear]