链接:旋转数组的最小数字_牛客题霸_牛客网 (nowcoder.com)
描述
有一个长度为 n 的非降序数组,比如[1,2,3,4,5],将它进行旋转,即把一个数组最开始的若干个元素搬到数组的末尾,变成一个旋转数组,比如变成了[3,4,5,1,2],或者[4,5,1,2,3]这样的。请问,给定这样一个旋转数组,求数组中的最小值。
数据范围:1 \le n \le 100001≤n≤10000,数组中任意元素的值: 0 \le val \le 100000≤val≤10000
要求:空间复杂度:O(1)O(1) ,时间复杂度:O(logn)O(logn)
示例1
输入:[3,4,5,1,2]
输出:1
方法一:二分查找
int minNumberInRotateArray(int* rotateArray, int rotateArrayLen ) {
// write code here
int l = 0;
int r = rotateArrayLen-1;
while(l < r)
{
int mid =(l+r) / 2;
if(rotateArray[r]>rotateArray[mid])
{
r = mid;
}
else if(rotateArray[mid]>rotateArray[r])
{
l = mid+1;
}
else
{
r = r-1;
}
}
return rotateArray[l];
}
方法二:找转折点
int minNumberInRotateArray(int* rotateArray, int rotateArrayLen ) {
// write code here
int i = 0;
for(i = 1;i<rotateArrayLen;i++)
{
if(rotateArray[i]<rotateArray[i-1])
{
return rotateArray[i];
}
}
return rotateArray[0];
}
方法二不能用i和i+1比较,是因为调换顺序的数组只有一个的时候会产生数组越界。