查找旋轉數組的最小值
Description:
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.
參考代碼:
class Solution {
public:
int findMin(vector<int>& nums)
{
int nRet = 0;
if(!nums.empty())
{
int mid;
int left = 0;
int right = nums.size()-1;
while(left < right)
{
mid = (left + right)/2;
// 最小值在左半部分
if(nums[mid] < nums[right])
{
right = mid;
}
// 最小值在右半部分
else if(nums[mid] > nums[right])
{
left = mid + 1;
}
}
nRet = nums[left];
}
return nRet;
}
};
小結:
1:充分使用有序數組的信息;
2:學會類似二分查找的思想;