题目描述:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
思路:
Python实现:
// An highlighted block
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if len(rotateArray) == 0:
return 0
ret = rotateArray[0]
if len(rotateArray) == 1:
return ret
for i in range(1, len(rotateArray)):
now = rotateArray[i]
if now < ret:
ret = now
break
return ret
python实现2:
思路:二分查找,当中间值大于左指针的值时,说明最小值在右边;当中间值小于右指正的值时,说明最小值在中间或者左边。
https://blog.csdn.net/iyuanshuo/article/details/79646899
// An highlighted block
# -*- coding:utf-8 -*-
class Solution:
def MinInOrder(self, rotateArray, left, right):
res = rotateArray[left]
for i in range(left, right+1):
if res > rotateArray[i]:
res = rotateArray[i]
return res
def minNumberInRotateArray(self, rotateArray):
# write code here
lenArr = len(rotateArray)
left, right = 0, lenArr-1
while left <= right:
if right - left == 1:
return rotateArray[right]
mid = (left + right)//2
if rotateArray[left] == rotateArray[mid] \
and rotateArray[mid] == rotateArray[right]:
return self.MinInOrder(rotateArray, left, right)
if rotateArray[mid] >= rotateArray[left]:
left = mid
elif rotateArray[mid] <= rotateArray[right]:
right = mid
return rotateArray[right]