1、题目描述
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
注意数组中可能存在重复的元素。
2、示例
输入: [2,2,2,0,1]
输出: 0
3、题解
C++基本思想:折半查找,和上一题的唯一区别就是对于3,3,1,3这种情况处理,如果左右两边数字相等,high--。
#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 (high >= 0 && nums[low] == nums[high])
high--;
while (low < high)
{
int mid = (low + high) / 2;
if (nums[mid] <= nums[high])
{
high = mid;
}
else
{
low = mid + 1;
}
}
return nums[low];
}
};
int main()
{
Solution solute;
vector<int> nums = { 3,3,1,3 };
cout << solute.findMin(nums) << endl;
return 0;
}