C++ stack and unordered_map


  • 0
    B

    first find ext greater element for all nums, then extract the result

    class Solution {
    public:
        vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
            stack<int>stk;
            unordered_map<int,int>next;
            for(auto e : nums)
            {//find next for all nums
                while(!stk.empty() && e > stk.top())
                {
                    next[stk.top()] = e;
                    stk.pop();
                }
                stk.push(e);
            }
            while(!stk.empty() )
            {
                next[stk.top()] = -1;
                stk.pop();
            }
            //extract answer
            vector<int>ans;
            for(auto e : findNums) ans.push_back(next[e]);
            return ans;
        }
    };

Log in to reply
 

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