Find Minimum in Rotated Sorted Array
Suppose an array sorted in ascending order 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.
所有的旋轉數組,都可以用這種方法來解決:
class Solution {
public:
int findMin(vector<int>& nums) {
int start = 0, end = nums.size()-1;
while(start<end) {
int mid = start + (end-start)/2;
if(nums[mid]<nums[end])
end = mid;
else if(nums[mid]>nums[end])
start = mid+1;
else
end--; //之所以要從end開始,是為了防止有序數比如:1 2 3,這種類型的case出現
}
return nums[start];
}
};