[Leetcode]力扣496:下一个更大元素I

在这里插入图片描述
思路
“下一个更大”的问题首先想到的就是单调栈结构
方法
维护一个单调减的栈,用map存储num2中下一个更大元素的对应关系

class Solution {
    
    
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
    
    
        stack<int> s;
        unordered_map<int, int> m;
        vector<int> res;
        for (int n: nums2) {
    
    
            while (!s.empty() && n > s.top()) {
    
      
                m[s.top()] = n;
                s.pop();
            }
            s.push(n);
        }
        while (!s.empty()) {
    
    
            m[s.top()] = -1;
            s.pop();
        }
        for (int n: nums1) {
    
    
            res.push_back(m[n]);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/112546558
今日推荐