503. Next Greater Element II

江枫思渺然 提交于 2020-01-09 00:27:15

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;
    }
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!