面试题8:旋转数组的最小数字
//面试题8:旋转数组的最小数字
//递增排序的{1,2,3,4,5}----->旋转为 {3,4,5,1,2} //求最小的数字
package com.hb.jzoffer; import offer.utilities.ArrayUtils; //面试题8:旋转数组的最小数字 //{1,2,3,4,5}----->旋转为 {3,4,5,1,2}
publicclass MinNumberInRotatedArray_8 {
public int Min(int[] array ) throws Exception{ int length = array.length ; if(length < 0){ Exception e = new Exception(); throw e; } int index1 = 0 ; int index2 = length - 1; int indexMid = index1 ; //如果下面while循环里面的不成立,说明数组是有序的,没有旋转,所以indexMid初始化为Index1 while(array[index1] >= array[index2]){ if(index2 - index1 == 1){ indexMid = index2; break ; } indexMid = (index1 + index2) / 2 ; //如果下标为index1 、index2 和 indexMid 指向的三个数字相等, //则只能用书序查找 if(array[index1] == array[index2] && array[indexMid] == array[index1]){ return MinInOrder(array , index1 , index2); } if(array[indexMid] >= array[index1]){ index1 = indexMid ; }else if(array[indexMid] <= array[index2]){ index2 = indexMid ; } } return array[indexMid]; } public int MinInOrder(int[] array , int index1 , int index2){ int result = array[index1]; for(int i = index1 + 1 ; i <= index2 ; i++){ if(result > array[i]){ result = array[i] ; } } return result; } public static void main(String[] args) throws Exception { int[] array = {3,4,5,1,2}; int[] array1 = {1,1,1,0,1}; MinNumberInRotatedArray_8 findMid = new MinNumberInRotatedArray_8(); int min = findMid.Min(array); int min1 = findMid.Min(array1); ArrayUtils.printArray(array); System.out.println(min); ArrayUtils.printArray(array1); System.out.println(min1); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。