binary search的变种。先设target=nums[end], 然后mid跟target比,如果nums[mid]>=target,则说明mid切在第2象限,此时扔掉左边边,否则说明mid切在第4象限,此时扔掉右半边。
while()循环完后的最小值的index要么是start,要么是end。再比较一下即可。
int findMin(vector<int> &nums) {
int start=0, end=nums.size()-1;
int target=nums[end];
while(start+1<end) {
int mid=start+(end-start)/2;
if (nums[mid]>=target) start=mid;
else end=mid;
}
if (nums[start]<=nums[end]) return nums[start];
else return nums[end];
}
二刷代码如下:
class Solution {
public:
/**
* @param nums: a rotated sorted array
* @return: the minimum number in the array
*/
int findMin(vector<int> &nums) {
int n = nums.size();
if (n == 0) return -1;
if (n == 1) return nums[0];
int start = 0, end = n - 1;
if (nums[end] > nums[start]) return nums[start]; //no wrapping
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid - 1] > nums[mid] && nums[mid + 1] > nums[mid]) return nums[mid];
if (nums[start] < nums[mid]) start = mid;
if (nums[start] > nums[mid]) end = mid;
}
if (nums[start] < nums[end]) return nums[start];
return nums[end];
}
};