C++ Easy to Understand O(n)

  • 0
    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 {
        vector<int> nextGreaterElements(vector<int>& nums) {
            deque<int> st;
            int L = nums.size();
            vector<int> ans(L, -1);
            if(L == 0)
                return ans;
            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;
                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.