class Solution {
public int minArray(int[] numbers) {
if(numbers==null || numbers.length<=0){
return 0;
}
int index1=0;
int index2=numbers.length-1;
int minIndex=index1;
while(numbers[index1]>=numbers[index2]){
//当只有数组只有两个元素 [5,1]
if(index2-index1==1){
minIndex=index2;
break;
}
//数组有两个以上元素[3,4,5,1,2]
minIndex=(index1+index2)/2;
//特殊情况:[1,0,1,1,1] [1,1,1,0,1] 按照顺序来查找
if(numbers[index1]==numbers[index2] && numbers[minIndex]==numbers[index1]){
return findNumber(numbers,index1,index2);
}if(numbers[minIndex]>=numbers[index1]){
index1=minIndex;//[5,1,2]
}else if(numbers[minIndex]<=numbers[index2]){
index2=minIndex;//[1,2]
}
}
return numbers[minIndex];
}
//当numbers[index1]==numbers[index2] && numbers[minIndex]==numbers[index1]时,或数组本身有序,按照顺序来查找
public int findNumber(int[] numbers,int index1,int index2){
int result=numbers[index1];
for(int i=index1+1;i<=index2;i++){
if(result>numbers[i]){
result=numbers[i];
}
}
return result;
}
}
旋转数组中得最小数字
最新推荐文章于 2022-08-19 18:37:51 发布