问题描述:
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4
5 6 7 0 1 2
).
Find the minimum element.
You may assume no duplicate exists in the array.
思考:
本以为遍历就好,但是想想这样的时间复杂程度为O(n),n为数组个数,所以更好的方法为二分法,复习下数据结构,二分法的时间复杂程度为O(logN),因为循环的次数随着每次个数的二分之一有关,例如while(l<=r),最开始l-r=128,那么后面就是64,32,16,8,4,2,1,0,-1,所以循环了9次,所以循环次数t(时间)和n的关系就是:
t = (log(n- 1))+2,因为只和log(n)有关,所以二分的时间复杂度就是O(logN),这道题的思路就是判断是否出现了递增情况(有序嘛)。
代码(java):
public class Solution {
public int findMin(int[] nums) {
int L = 0, R = nums.length-1;
//出现了递减情况,就找到了最小值了
while (nums[L] > nums[R]) {
int M = (L + R) / 2;
//中点在最小值的左边,所以坐指针需要前移
if (nums[M] > nums[R]) {
L = M + 1;
} else {
//避免中点跑到了最小值的右边
R = M; // be careful, not mid-1
}
}
return nums[L];
}
}