本文共 2046 字,大约阅读时间需要 6 分钟。
题目描述:
把一个数组最开始的若干个元素搬到数组的末尾 我们称之为数组的旋转
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素思路:
分析旋转数组的特点,例如{3,4,5,1,2},因为是旋转数组,因此不存在数组整个是递增序列。 最小元素的左边的是比它大的数且依次递增,右边同样的是比它大的递增序列,因此可以使用二分查找,三个指针分别指向首元素、尾元素和中间元素。public static int minElementInRotateArray(int[] array) { int leftIndex = 0, rightIndex = array.length - 1, midIndex = (rightIndex + leftIndex) / 2; while (leftIndex < rightIndex - 1) { if (array[leftIndex] == array[midIndex] && array[rightIndex] == array[midIndex]) { //三者相同 无法判断 因此进行顺序查找 return minElementBySort(array); } else { if (array[midIndex] >= array[leftIndex]) { leftIndex = midIndex; } else { rightIndex = midIndex; } midIndex = (rightIndex + leftIndex) / 2; } } return array[rightIndex]; } private static int minElementBySort(int[] ints) { int minElement = ints[0]; for (int i = 1; i < ints.length; i++) { if (ints[i] < minElement) { minElement = ints[i]; } } return minElement; }
测试:
@RunWith(Parameterized.class)public class RotateArrayTest extends BaseTest { @Parameterized.Parameters public static List
转载地址:http://yhqli.baihongyu.com/