把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1
这个题可以借助二分查找的思想:
二分查找的时间复杂度是:O(logn)
/** *题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转, * 输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1 *时间:2015年8月27日10:40:25 *文件:Min.java *作者:cutter_point */ package bishi.Offer50.y2015.m08.d27; public class Min { /** * 用二分法求旋转数组中最小的值 * @param numbers * @return * @throws Exception */ public static int getMin(int numbers[]) throws Exception { if(numbers == null) { throw new Exception("数组为空"); }//if int minnumber = 0; int start = 0; int end = numbers.length - 1; int mid = start; while(start < end) { if((end - start) == 1) { minnumber = numbers[end]; break; }//if mid = (start + end) / 2; //考虑到当start和end还有mid3个地方的值相同的时候 //采用顺序查找 if(numbers[start] == numbers[mid] && numbers[mid] == numbers[end]) { return MinOrder(numbers, start, end); }//if if(numbers[mid] > numbers[start]) { start = mid; }//if else { end = mid; }//else }//while return minnumber; } public static int MinOrder(int numbers[], int index1, int index2) { int result = numbers[index1]; while(index1 <= index2) { if(result > numbers[index1]) result = numbers[index1]; ++index1; }//while return result; } public static void main(String[] args) { int array[] = {3,4,5,0,1,1,2,3}; int array2[] = {1,0,1,1,1}; try { System.out.print(getMin(array)); } catch (Exception e) { e.printStackTrace(); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/cutter_point/article/details/48027409