Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.git
(i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
).github
Find the minimum element.web
You may assume no duplicate exists in the array.数组
Example 1:yii
Input: `[3,4,5,1,2]` Output: 1
Example 2:svg
Input: `[4,5,6,7,0,1,2]` Output: 0
题目:旋转(有序)数组中的最小值,假设数组中无重复元素。spa
思路:二分查找,参见Compact and clean C++ solution。对于旋转数组[4,5,6,7,0,1,2]
而言,最小值落在后半段有序数组的首位。nums[start] > nums[end]
;对于mid = start + (end - start)/2
,若是nums[start] > nums[mid]
,说明mid
落在了后半段有序的数组中,那么最小值落在[start, mid]
之间,若是nums[start] < nums[mid]
,说明mid
落在了前半段有序的数组中,那么最小值在[mid, end]
之中。code
工程代码下载xml
class Solution { public: int findMin(vector<int>& nums) { int r = nums.size() - 1; int l = 0; while(l < r){ if(nums[l] < nums[r]) //数组已经有序 return nums[l]; int mid = l + (r - l)/2; if(nums[l] > nums[mid]) r = mid; else l = mid + 1; } return nums[l]; } };
class Solution { public: int findMin(vector<int>& nums) { int r = nums.size() - 1; int l = 0; while(l < r){ int mid = l + (r - l)/2; if(nums[mid] > nums[r]) l = mid + 1; else r = mid; } return nums[l]; } };
若是数组中存在重复元素。token
class Solution { public: int findMin(vector<int> &num) { int lo = 0; int hi = num.size() - 1; int mid = 0; while(lo < hi) { mid = lo + (hi - lo) / 2; if (num[mid] > num[hi]) { lo = mid + 1; } else if (num[mid] < num[hi]) { hi = mid; } else { // when num[mid] and num[hi] are same hi--; } } return num[lo]; } };
When
num[mid] == num[hi]
, we couldn’t sure the position of minimum inmid
's left or right, so just let upper bound reduce one.