旋转数组的最小数字
问题描述:输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素,例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1
常规方法:遍历数组,找到min即可,时间复杂度为On.
本方法思想:类似于二分查找,每次从中间查找,将数组分成两部分。因为数组是递增的,因此分成的两个数组的最后一个数(结束)有一个比第一个数(起始)小,比如{3,4},{5,1,2},第二个数组的最后一个数字2比起始5小,那么最小的值就在这个数组中。
持续更新...
代码附下
Java实现:
package 旋转数组的最小数字;
/**
* 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
* 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1
* @author user
*
*/
public class Test {
public static void main(String[] args) {
int[] a = { 6, 7, 8, 9, 0, 2, 3, 4 };
int min = findMin(a);
System.out.println(min);
}
private static int findMin(int[] a) {
int start = 0;
int end = a.length - 1;
int mid = 0;
while (start < end) {
if (start + 1 == end) {
return a[end];
}
mid = (start + end) / 2;
if (a[mid] >= a[start]) {
start = mid;
} else {
end = mid;
}
}
System.out.println("没找到!");
return -1;
}
}
持续更新...欢迎赞赏!![](https://i-blog.csdnimg.cn/blog_migrate/ca0cc5c488ad24501c0bbddad6302b17.png)
https://blog.csdn.net/ustcer_93lk/article/details/80368865
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。