C++ Easy to Understand O(n)


  • 0
    H
    1. Put elements int a stack in decreasing order.
    2. With a new element v, when the front is smaller than v, do:
      pop, and make v its greater number.
    3. Push v into stack.
    class Solution {
    public:
        vector<int> nextGreaterElements(vector<int>& nums) {
            deque<int> st;
            int L = nums.size();
            vector<int> ans(L, -1);
            if(L == 0)
                return ans;
            st.push_front(0);
            int i= 1%L;
            for(int j=0;j<2*L;j++){
                int v = nums[i];
                while(!st.empty() && v > nums[st.front()]){
                    ans[st.front()] = v;
                    st.pop_front();
                }
                st.push_front(i);
                i ++;
                i %= L;
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.