把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
第一种思路是提交了的代码中的最上边的几种解法
第二种思路来自于一本书,总体是采用的二分的思想,考虑二分之后最小值可能所处的位置
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
pre = -7e20
for num in rotateArray:
if num < pre:
return num
pre = num
if len(rotateArray) == 0:
return 0
return rotateArray[0]
# 二分的思路
def minNumberInRotateArray2(self, rotateArray):
low=0
high=len(rotateArray)-1
mid=0
while low<high:
if low==high-1:
break
if rotateArray[low]<rotateArray[high]:
return rotateArray[low]
mid=(low+high)//2
if(rotateArray[low]>rotateArray[mid]):
high=mid
continue
if rotateArray[mid]>rotateArray[high]:
low=mid
continue
while low<mid:
if rotateArray[low]==rotateArray[mid]:
low+=1
elif rotateArray[low]<rotateArray[mid]:
return rotateArray[low]
else:
high=mid
break
return min(rotateArray[low],rotateArray[high])