旋转数组中的最小值(C++实现|测试用例)
代码:
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
//一遍数组遍历
int findMin(vector<int>& nums) {
int min=nums[0];
int numsize = nums.size();
for(int i=1;i<numsize;i++)
{
if(nums[i]<=min)
{
min=nums[i];
}
}
return min;
}
//二分查找法
int findMin_1(vector<int>&nums){
int left =0;int right = nums.size()-1;
if(nums.size()==0)
{
return -1;
}
while(left<right)
{
int mid = left+(right-left)/2;
if(nums[mid]<nums[right])
{
right=mid;
}
else if(nums[mid]>nums[right])
{
left = mid + 1;
}
else{
right--;
}
}
return nums[left];
}
};
int main()
{
vector<int> v={7,8,9,3,4,5,6};
Solution s;
cout<<s.findMin(v)<<'\n'<<s.findMin_1(v);
}