C++ solution easy to understand


  • 0
    Q
    class Solution {
    public:
        vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
            vector<int> res;
            map<int,int> mp;
            stack<int> s;
            int li = 0;
            for(int i=0;i<nums.size();i++){
                int cur = nums[i];
                while(!s.empty() && cur > s.top()){
                    int t = s.top();
                    s.pop();
                    mp[t] = cur;
                }   
                s.push(cur);
            }
            for(auto it:findNums){
                if(mp.find(it) != mp.end())
                    res.push_back(mp[it]);
                else
                    res.push_back(-1);
            }
            
            return res;
        }
    };
    

Log in to reply
 

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