[LeetCode] 503, the next larger element||

Article directory

1. The topic

503. Next Larger Element ||

2. Ideas

To find the next larger element, it can be implemented with a monotonic stack. This article uses a monotonic decreasing stack (decreasing from the bottom of the stack to the top of the stack)

Circulating arrays can be simplified by arranging two arrays in sequence. We start with i from 2*nums.size(), and traverse the elements from right to left. If the element is larger than the top of the stack, the top of the stack needs to be popped out of the stack. into the ans array.

3. Coding

#include <iostream>
#include<vector>
#include <stack>

using namespace std;

vector<int> nextGreaterElements(vector<int>& nums) {
    
    
    stack<int> st;
    int sz = nums.size();
    vector<int> ans(sz);
    for (int i = 2 * nums.size() - 1; i >= 0; i--) {
    
    
        int num = nums[i%sz];
        while(!st.empty() && num >= st.top()) {
    
    
            st.pop();
        }
        ans[i%sz] = st.empty() ? -1 : st.top();
        st.push(num);
    }
    return ans;
}

int main() {
    
    
    vector<int> v = {
    
    1,2,3,4,3};
    nextGreaterElements(v);
    return 0;
}

Guess you like

Origin blog.csdn.net/jiaoyangwm/article/details/127466808