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];
}
};
网友评论