I. Question
Given an sorted array, the array may increase monotonically or may have a transformation.
(I. e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2)
The minimum number is required.
Ii. Analysis
This question is divided into two situations as described in the question.
1. Strictly monotonic increasing
2. There is an inflection point
We need to process the problem by case. Of course, we can traverse the problem directly, that is, scanning from start to end to find the minimum number.
1. When strictly monotonous, we can directly return the first element because it is sorted; or we can directly use the bipartite search.
2. When there is an inflection point, we can quickly find the minimum value in binary search.
In summary, two situations can improve efficiency, but they can be better handled directly as one case. And can pass.
class Solution {public: int findMin(vector<int> &num) { int min = num[0]; for(int i=1;i<num.size();i++){ if(num[i]>num[i-1]) min = num[i]; } return min; }};class Solution {public: int findMin(vector<int> &num) { if(num.size()==0) return 0;int sta=0;int flag; int end=num.size()-1; while(sta<end){ flag = (sta+end)/2; if(num[flag]<num[end]) end=flag; else sta=flag+1; } return num[sta]; }};class Solution {public: int findMin(vector<int> &num) { int cou=num.size()-1; //the numbers of num if(num.size()==0) return 0; //the num is null if(num.size()==1) return num[0]; //num have a single numberint mid=0;int sta=0; //the start int end=cou; //the end if(num[sta]<num[end]) { //Monotonically increasingreturn num[0];}else { //There are situations inflection point while(sta<end){mid = (sta+end)/2;if(num[mid]<num[end]) end=mid; else sta=mid+1;}return num[end]; } }};
Leetcode: find_minimum_in_rotated_sorted_array