503. The next larger element II (monotonic stack in the case of numbers forming a ring)

Given a looping array (the next element of the last element is the first element of the array), output the next larger element of each element. The next larger element of the number x is in the array traversal order. The first number after this number is larger than it, which means you should search for the next larger number in a loop. If it does not exist, -1 is output.

Example 1:

Input: [1,2,1]
Output: [2,-1,2]
Explanation: The next greater number of the first 1 is 2; the
number 2 cannot find the next greater number; the
second The next largest number of 1 requires a loop search, and the result is also 2.
Note: The length of the input array will not exceed 10,000.

analysis:

When encountering the problem of ring formation , the most direct way to think of the problem of "Taking a Family and Robbery II" is to traverse twice. Putting it in a for loop will result in many values ​​greater than nums.size(). It is troublesome to modify the nums array. In this question, you can use the idea of ​​taking the modulus of nums.size(), the monotonic stack part is still to find the next largest, and construct a monotonic decreasing stack. The code is as follows:

class Solution {
    
    
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
    
    
        int len = nums.size();
        if(len < 1) return vector<int>{
    
    };
        else if(len == 1) return vector<int>{
    
    -1};
        // 找下一个更大,构造递减单调栈
        stack<int> st;
        vector<int> res(nums.size(), -1); // 如果不存在则输出-1
        // 成环问题,2倍数组长度拆成链
        for(int i = 0; i < len * 2; i++){
    
    
            if(st.empty() || nums[i % nums.size()] <= nums[st.top()]){
    
    
                st.push(i % nums.size());
            }else{
    
    
                while(!st.empty() && nums[i % nums.size()] > nums[st.top()]){
    
    
                    res[st.top()] = nums[i % nums.size()];
                    st.pop();
                }
                st.push(i % nums.size());
            }
        }
        return res;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34612223/article/details/114435912