// 题目:输入一个旋转数组,输出其中的最小值
// 解法:使用二分法进行查找
public class Main {
public static void main(String[] args) {
System.out.println(findMinNum(new int[]{1,0,1,1,1}));
}
public static int findMinNum(int[] input){
int low = 0;
int high = input.length-1;
int mid = low;
while(input[low]>=input[high]){
if(high-low == 1){ //如果high-low = 1,则返回high的值,因为high的值一定小于等于low的
mid = high;
break;
}
mid = (low+high)/2;
if(input[low] == input[high] && input[mid] == input[low]){ //如果出现low,mid,high都相等,则只能顺序查找
return minInOrder(input, low, high);
}
if(input[mid]>=input[low]){ //如果mid>=low则最小值在mid和high之间
low = mid;
}
if(input[mid]<=input[high]){ //如果mid<high则最小值在low和mid之间
high = mid;
}
}
return input[mid];
}
public static int minInOrder(int[] input, int low, int high){ //顺序查找函数
int result = input[low];
for(int i = low+1;i<=high;i++){
if(input[i]<result){
result = input[i];
}
}
return result;
}
}
剑指offer 8. 旋转数组的最小数字
最新推荐文章于 2025-08-19 18:46:01 发布