旋转数组中的最小数字,剑指offer,P70 二分查找来实现O(logn)的查找

时间:2020-12-23 10:46:13
public class MinNumberInRotatedArray {

    public int getMinNumInRotatedArray(int[] array) {
if(array == null) {
return -1;
}
int leftIndex = 0;
int rightIndex = array.length - 1;
if(array[leftIndex] == array[rightIndex]) {
return array[0];
}
int midIndex = leftIndex;
while(array[leftIndex] >= array[rightIndex]) {
// while(true) { 换成这个其实一样
if(rightIndex - leftIndex <= 1) {//循环退出的条件
midIndex = rightIndex;
break;
}
midIndex = (leftIndex+rightIndex)/2;
if(array[leftIndex] == array[rightIndex] && array[leftIndex] == array[midIndex]) {//如果两边的值和中间的值相等,
//则无法判断中间值在左边还是在右边,因此只能进行顺序查找
minNumBySort(array, leftIndex, rightIndex);
}
if(array[leftIndex] <= array[midIndex]) {
leftIndex = midIndex;
}else if(array[rightIndex] >= array[midIndex]){
rightIndex = midIndex;
}
}
return array[midIndex];
} public int minNumBySort(int[] arr, int leftIndex, int rightIndex) {
int result = arr[leftIndex];
for(int i = leftIndex; i < rightIndex; i++) {
if(arr[i] < result) {
result = arr[i];
}
}
return result;
} public static void main(String[] args) {
MinNumberInRotatedArray testArray = new MinNumberInRotatedArray();
int[] array = {4,5,6,1,2,3};
System.out.println(testArray.getMinNumInRotatedArray(array));
}
}