Sword refers to offer acwing 22 The smallest number of the rotating array (two points)

Topic

Insert picture description here

answer

  1. The question says that the input is a rotation sequence of an ascending sequence, that is, for example, an ascending sequence is 1 2 3 4 5
    , you can enter 4 5 1 2 3 in the question, and then let you find the smallest one. (There will be repeated numbers in the sequence)
  1. We use the abscissa to indicate the subscript of the sequence, and the ordinate to indicate the size of the sequence value
    Insert picture description here
    will get such a graph (the previous interval is above the latter, and it is obtained by rotating). We find that except for the last horizontal segment (black level) Except for that paragraph), the rest satisfies the dichotomous property: the number on the left of the vertical dotted line satisfies nums[i]≥nums[0]; the number on the right of the vertical dotted line does not satisfy this condition. The demarcation point is the minimum value of the entire array.
  1. So we can delete the last level first. In addition, don't forget to deal with the special case of the array being completely monotonous: when we delete the last level of a paragraph, if the last remaining number is greater than or equal to the first number, then the array is completely monotonous.
  1. The time complexity of dichotomy is O(logn), and the worst time complexity of deleting the last level segment is O(n), so the total time complexity is O(n).

Code

class Solution {
    
    
public:
    int findMin(vector<int>& nums) {
    
    
        
        int n=nums.size()-1;
        if(n<=0) return -1;
        while(n>0 && nums[n]==nums[0]) n--;  //删掉末尾元素
        if(nums[n]>=nums[0]) return nums[0]; //删完后就是单调
        
        int l=0,r=n;
        while(l<r){
    
    
            int mid=(l+r)>>1;
            if(nums[mid]<nums[0]) r=mid;
            else l=mid+1;
        }
        return nums[l];
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114901880