题目:把一个数组最开始的若干个 元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3, 4, 5, 1, 2}为{1, 2, 3, 4, 5}的一个旋转,该数组的最小值为1.
/** * 面试题8 * * 2014-1-14 */ public class MinNumberInRotatedArray { public int findMin(int[] data) { if (data == null || data.length <= 0) { throw new NullPointerException(); } if (data.length == 1) { return data[0]; } // 全相等 return handleFindMin(data); } private int handleFindMin(int[] data) { int length = data.length; int rightValue = data[length-1]; int rightIndex = length-1; int leftIndex = 0; // 左侧指针向右走 while (leftIndex < rightIndex) { if (data[leftIndex] >= rightValue) { leftIndex++; } else { // 大意了,进入了死循环 break; } } System.out.println("left Index = " + leftIndex); return data[leftIndex]; } public static void main(String[] args) { int[] arr1 = {3, 4, 5, 1, 2}; MinNumberInRotatedArray instance = new MinNumberInRotatedArray(); int min1 = instance.findMin(arr1); System.out.println("数组1最小值是 = " + min1); int[] arr2 = {1, 1, 1, 0, 1}; int min2 = instance.findMin(arr2); System.out.println("数组2最小值是 = " + min2); } }