1、题目描述
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
你可以假设数组中不存在重复元素。
2、示例
输入: [3,4,5,1,2]
输出: 1
3、题解
基本思想:折半查找
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
int findMin(vector<int>& nums) {
//基本思想:折半查找
int low = 0, high = nums.size() - 1;
while (low < high)
{
int mid = (low + high) / 2;
if (nums[mid] < nums[high])
{
high = mid;
}
else if (nums[mid] > nums[high])
{
low = mid + 1;
}
}
return nums[low];
}
};
int main()
{
Solution solute;
vector<int> nums = { 1,2,3 };
cout << solute.findMin(nums) << endl;
return 0;
}