把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
示例 1:
输入:[3,4,5,1,2]
输出:1
示例 2:
输入:[2,2,2,0,1]
输出:0
Python 解答:
1.线性扫描
class Solution:
def minArray(self, numbers: List[int]) -> int:
length = len(numbers)
if length == 1:
return numbers[0]
for i in range(length-1):
if numbers[i] <= numbers[(i+1)]:
if i == length-2:
return numbers[0]
continue
else:
return numbers[(i+1)]
2.二分查找
class Solution:
def minArray(self, numbers: List[int]) -> int:
def find(numbers, left, right):
mid = (left+right) // 2
if left < right:
if numbers[mid] < numbers[right]:
return find(numbers, left, mid)
elif numbers[mid] > numbers[right]:
return find(numbers, mid+1, right)
else:
return find(numbers, left, right-1)
else:
return numbers[right]
return find(numbers, 0, len(numbers)-1)
留言