c++ - std::stack<int> 具有最大功能?

标签 c++ algorithm

如何实现 stack<int>使用最大操作,最大函数的复杂度为 O(1) 并且它使用 O(n) 额外内存?

最佳答案

想法是通过在堆栈中使用对来跟踪最大值。如果你向堆栈中插入一些东西,你会相应地更新最大值。

class Stack {
private: 
    stack<pair<int,int>> s;

public:
    bool empty() const {
        return s.empty();
    }

    int max() const {
        assert (empty() == false);
        return s.top().second;
    }

    int pop() {
        int ans = s.top().first;
        s.pop();
        return ans;
    }

    void push(int x) {
        if (s.empty() || x > s.top().second)
        {
            s.emplace(x, x);
        }
        else
        {
            s.emplace(x, s.top().second);
        }
    }
};

关于c++ - std::stack<int> 具有最大功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34030327/

相关文章:

c++ - std::ptr_fun 模板化类和结构的参数困难

c++ - 右移数组

c++ - 如何使用 Clang 从此示例中获取基类?

c++ - 使用 BOOST.python 将结构从 C++ 返回到 Python

c++ - 程序卡在 wait()

Facebook 编程挑战赛 - ByteLand

algorithm - 一系列文件的最短压缩时间

javascript - 求补数的有效解

java - 寻找有关 trie 的良好介绍

algorithm - 如何在具有最大平均子集大小的等距子集上拆分集?