- 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
这是一个查找题目,查找有顺序查找,折半查找和分块查找。其中对于有序表的查找应该采用折半查找。采用三个指针。
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
j = 0
for i in range(1,len(rotateArray)-1):
if rotateArray[i]<rotateArray[i-1]:
j=i
if rotateArray[j]>rotateArray[0]:
return rotateArray[0]
else :
return rotateArray[j]
上面的这个算法的时间复杂度为O(n),他用的是顺序查找,其实这是一个相对有序的序列,我们可以用二分查找。
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
low = 0
high = len(rotateArray)-1
while (low < high):
mid = low + (high - low) / 2
if rotateArray[mid]>rotateArray[high]:
low = mid+1
elif rotateArray[mid]==rotateArray[high]:
high = high-1
else:
high = mid
return rotateArray[low]