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.
一开始理解错了意思,以为题目是可以rotate很多次,于是自己把自己转晕了,在明确了题意之后,很快出来了第一种解法
class Solution {
public:
int findMin(vector<int>& nums) {
int left=0;
int right=nums.size()-1;
if(nums.size()==0)
{
return 0;
}
if(nums[left]<nums[right])
{
return nums[left];
}
else{
while(nums[left]>nums[right])
{
left++;
}
return nums[left];
}
}
};
后来看了网上流传的版本(二分查找法,思路不清楚的经常会被绕晕呀,遂从网上copy之)
class Solution {
public:
int findMin(vector<int>& nums) {
if(nums.empty())
return 0;
if(nums.size() == 1)
return nums[0];
int n = nums.size();
int low = 0;
int high = n-1;
while(low < high && nums[low] > nums[high]) //此处注意后面的条件 nums[low]>nums[high].否则就可能会造成答案错误
{
int mid = low + (high-low)/2;
if(nums[mid] < nums[low]) // mid is in second part
high = mid; //此处注意不是mid+1,否则就可能跳过最低点
else if(nums[mid] == nums[low]) // since (low<high)-->(low+1==high)
return nums[high]; // nums[low]>nums[high]
else
low = mid+1;
}
return nums[low];
}
};