Jianzhi Offer [Array] 03. The smallest number in the rotation array

insert image description here
Idea:
    To query the maximum and minimum values ​​in an array, the dichotomy method is generally used, that is, to control two pointers and approach them from both sides.

(1) Traversal method: time complexity o(n)
    Since the rotating array and the original array of this question are in ascending order, as long as the number after the array appears is smaller than the previous number, then the latter number must be the minimum value of the array, and traversal is used The method of comparing the previous and the next number respectively can find the minimum value.

class Solution {
    
    
public:
    int minArray(vector<int>& numbers) {
    
    
        for(int i=1;i<numbers.size();i++)
            if(numbers[i]<numbers[i-1]) return numbers[i];
        
        return numbers[0];
    }
};

insert image description here

(2) Dichotomy time complexity o(logn)
Feasibility:
    set the minimum value as the rotation point, the numbers on the left side of the rotation point are greater than the rotation point, and the numbers on the right side are smaller than the rotation point, so set up three positions: left, right and middle , compare the right and middle values. If the middle is large, it means that the rotation point is not on the left. In the same way, other situations can be obtained. Continue to judge the rotation center by moving the left and right positions. When the left and right positions are the same, it means that the position of the minimum value has been found. .

Correctness:
insert image description here

class Solution {
    
    
public:
    int minArray(vector<int>& numbers) {
    
    
        int i = 0, j = numbers.size() - 1;
        while (i < j) {
    
    
            int m = (i + j) / 2;
            if (numbers[m] > numbers[j]) i = m + 1;
            else if (numbers[m] < numbers[j]) j = m;
            else j--;
        }
        return numbers[i];
    }
};

insert image description here

Guess you like

Origin blog.csdn.net/daweq/article/details/129851059