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;
}