c++ solution using stack


  • 0
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) 
    {
        vector<int> result;
        unordered_map<int, int> map; // record num and it next greater element
        stack<int> st;
        
        for (auto num : nums)
        {
            while (!st.empty() && (st.top() < num))
            {
                map[st.top()] = num;
                st.pop();
            }
            st.push(num);
        }
    
        for (auto num : findNums)
            result.push_back(map.count(num) ? map[num] : -1);
        
        return result;
    }

Log in to reply
 

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