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