C++ Stack solution very easy to understand


  • 0
    Q
    class Solution {
    public:
        vector<int> nextGreaterElements(vector<int>& nums) {
            vector<int> res(nums.size(),-1);
            map<int,int> mp;
            stack<int> s; //index
            for(int i=0;i<nums.size();i++){
                int cur = nums[i];
                while(!s.empty() && cur > nums[s.top()]){
                    int t = s.top();
                    s.pop();
                    res[t] = cur;
                }
                s.push(i);
            }
            
            for(int i=0;i<nums.size();i++){
                while(!s.empty() && nums[i] > nums[s.top()]){
                    int t = s.top();
                    s.pop();
                    res[t] = nums[i];
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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