'''
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
'''
class Solution:
def minNumberInRotateArray1(self, rotateArray):
if len(rotateArray) == 0:
return 0
front = 0
rear = len(rotateArray) - 1
minVal = rotateArray[0]
if rotateArray[front] < rotateArray[rear]:
return rotateArray[front]
else:
while (rear - front) > 1:
mid = (rear + front)//2
if rotateArray[mid] > rotateArray[rear]:
front = mid
elif rotateArray[mid] < rotateArray[front]:
rear = mid
elif rotateArray[mid] == rotateArray[front] and rotateArray[front] == rotateArray[rear]:
for i in range(1, len(rotateArray)):
if rotateArray[i] < minVal:
minVal = rotateArray[i]
rear = i
minVal = rotateArray[rear]
return minVal
def minNumberInRotateArray2(self, rotateArray):
if len(rotateArray) == 0:
return 0
front = 0
rear = len(rotateArray) - 1
midIndex = 0
while rotateArray[front] >= rotateArray[rear]:
if rear - front == 1:
midIndex = rear
break
midIndex = (front + rear) // 2
if rotateArray[front] == rotateArray[rear] and\
rotateArray[front] == rotateArray[midIndex]:
return self.MinInOrder(rotateArray, front, rear)
if rotateArray[midIndex] >= rotateArray[front]:
front = midIndex
elif rotateArray[midIndex] <= rotateArray[rear]:
rear = midIndex
return rotateArray[midIndex]
def MinInOrder(self, array, front, end):
# 如果前中后三个指针相等时,我们无法判断,只能顺序查找
result = array[0]
for i in array[front:end-1]:
if i < result:
result = i
return result
if __name__ == '__main__':
solution = Solution()
print(solution.minNumberInRotateArray1([3, 4, 5, 1, 2]))
print(solution.minNumberInRotateArray2([3, 4, 5, 1, 2]))
print(solution.minNumberInRotateArray2([1, 2, 3, 4, 5]))
print(solution.minNumberInRotateArray1([1, 1, 1, 0, 1]))
print(solution.minNumberInRotateArray2([]))
print(solution.minNumberInRotateArray2([1]))
剑指offer python版 11.旋转数组的最小数字
最新推荐文章于 2022-04-09 22:00:00 发布