[Leetcode] 716. Max Stack 解题报告

本文介绍了一种设计支持push、pop、top、peekMax和popMax操作的最大值栈的方法。通过使用list和map两种数据结构,实现了这些操作的高效执行。具体而言,list用于模拟栈的基本操作,而map则用于快速检索和移除最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Design a max stack that supports push, pop, top, peekMax and popMax.

  1. push(x) -- Push element x onto stack.
  2. pop() -- Remove the element on top of the stack and return it.
  3. top() -- Get the element on the top.
  4. peekMax() -- Retrieve the maximum element in the stack.
  5. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.

Example 1:

MaxStack stack = new MaxStack();
stack.push(5); 
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5

Note:

  1. -1e7 <= x <= 1e7
  2. Number of operations won't exceed 10000.
  3. The last four operations won't be called when stack is empty.

思路

我们定义两个数据结构:1)list<int>用来模拟栈,这样可以实现push,pop和top;2)map<int, vector<list<int>::iterator>>,用来实现peekMax和popMax,因为我们可以从map中利用O(1)的时间复杂度得到最大的数,而由于我们在map中也同时保存了各个数对应的迭代器,所以也可以在O(1)的时间复杂度内删除掉list中的内容。

这样的话,可以保证push和pop的时间复杂度为O(logn),top,peekMax,popMax的时间复杂度都为O(1)。整个算法的空间复杂度为O(n)。我感觉应该是最优的算法了。

代码

class MaxStack {
public:
    /** initialize your data structure here. */
    MaxStack() {
        
    }
    
    void push(int x) {
        auto it = l.insert(l.end(), x);
        m[*it].push_back(it);
    }
    
    int pop() {
        auto it = l.end();
        --it;
        int value = *it;
        m[*it].pop_back();
        if (m[*it].empty()) {
            m.erase((*it));
        }
        l.erase(it);
        return value;
    }
    
    int top() {
        return *(l.rbegin());
    }
    
    int peekMax() {
        return m.rbegin()->first;
    }
    
    int popMax() {
        auto it = m.rbegin()->second.back();
        int value = m.rbegin()->first;
        m.rbegin()->second.pop_back();
        if (m.rbegin()->second.empty()) {
            m.erase(m.rbegin()->first);
        }
        l.erase(it);
        return value;
    }
private:
    list<int> l;
    map<int, vector<list<int>::iterator>> m;
};

/**
 * Your MaxStack object will be instantiated and called as such:
 * MaxStack obj = new MaxStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.peekMax();
 * int param_5 = obj.popMax();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值