503. Next Greater Element II

https://leetcode.com/problems/next-greater-element-ii/description/

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        stack<int> st;
        int n = nums.size();
        for (int i = 2 * n - 1; i >= n; i--) {
            int cur = nums[i % n];
            while (!st.empty() && cur >= st.top())
                st.pop();
            st.push(cur);
        }
        
        vector<int> res(n, 0);
        for (int i = n - 1; i >= 0; i--) {
            int cur = nums[i];
            while (!st.empty() && cur >= st.top())
                st.pop();
            if (st.empty())
                res[i] = -1;
            else
                res[i] = st.top();
            st.push(cur);
        }
        
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/JTechRoad/p/8990477.html