offer11旋转数组的最小数字python
作者:互联网
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
解题思路有两种
python
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
#方法一,挨个遍历将最小的
#minnum = 0
#for i in range(len(rotateArray)):
#minnum = minnum if minnum < rotateArray[i] and minnum != 0 else rotateArray[i]
#return minnum
#方法二 使用二分查找,非递减数列,则最右侧的数小于中间数,说明中间肯定有断崖,最小值就在中间到最右侧之间;若最右侧数大于中间数,说明最小值在中间到最左侧之间。
if len(rotateArray) == 0:
return 0
right = len(rotateArray) - 1
left = 0
while left <= right:
mid = (right + left)/2
if rotateArray[mid] < rotateArray[mid - 1]:
return rotateArray[mid]
elif rotateArray[mid] < rotateArray[right]:
right = mid - 1
else:
left = mid + 1
return 0
java
class Solution {
public int minArray(int[] numbers) {
int i = 0;
int j = numbers.length-1;
while (i < j){
int m = (i+j)/2;
if (numbers[j]>numbers[m]){
j = m;
} else if (numbers[j] < numbers[m]){
i = m+1;
} else{
j = j-1;
}
}
return numbers[i];
}
}
标签:python,旋转,int,minnum,offer11,numbers,数组,rotateArray 来源: https://www.cnblogs.com/Harrypoter/p/16385141.html