【Leetcode】【Medium】Find Minimum in Rotated Sorted Array
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)的解法,所以题目是为了考察用二分搜索实现o(logn)的解法;
当num[start] < num[end]时,说明原数列没有旋转,或者整旋转了一圈回到了原点,所以num[start]是最小值;
同理,只要是首比尾小,都表示有序,那么最小值一定在乱序里,这样就可以用mid去中间值,做判断,每次缩小一半范围;
注意:
不用每次都用递归,使用start和end表示操作的下标就可以了;
中值mid = (start+end)/2,mid的值可能等于start,但是不会等于end,所以每次start=mid+1 或者 end = mid,就一定能保证每次更新下标值,不会陷入死循环;
代码:
1 class Solution { 2 public: 3 int findMin(vector<int> &num) { 4 int start = 0; 5 int end = num.size() - 1; 6 7 while (start < end) { 8 if (num[start] < num[end]) 9 return num[start]; 10 int mid = (start + end) / 2; 11 if (num[start] <= num[mid]) 12 start = mid + 1; 13 else 14 end = mid; 15 } 16 17 return num[start]; 18 } 19 };