Stack - Min Stack

来源:互联网 发布:电视直播软件live官网 编辑:程序博客网 时间:2024/06/06 01:34

https://leetcode.com/problems/min-stack/

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

很多题目,只要把过程模拟一下,基本上算法呼之欲出,不过若是想优化,则需要更多的经验方面的积累了。

最自然的思路是额外再维护一个栈,与数据栈同步,不过内容是当前栈的最小值。之后可以考虑,如果入栈的值大于当前的最小值,那么,这个值肯定不可能是最小值,所以,最小值所对应的栈也没必要每次都执行入栈操作,只有在当前值小于等于最小值时,才入栈。

其实也不需要额外使用一个栈的,只需要额外维护一个变量即可。事后诸葛亮一下,需要用的数据有两类,一类是栈中数据,一类是当前的最小值(只有一个),若是可以建立起这两类数据的关联,可能也便不需要额外维护一个栈了。

如何建议关联?运算!

用什么运算?加减法(stack中元素的运算应统一规则 – x - smin)!

需要注意的是,有可能溢出,所以元素的类型应为 64 位(long long)。

class MinStack { // Runtime: 32 mspublic:    void push(int x) {        s.push(x);        if (smin.empty()) {            smin.push(x);        }        else {            // smin.push(min(smin.top(), x));            if (x <= smin.top()) {                smin.push(x);            }        }    }    void pop() {        if (!s.empty()) {            // smin.pop();            if (s.top() == smin.top()) {                smin.pop();            }            s.pop();        }    }    int top() {        if (s.empty()) {            return 0;        }        return s.top();    }    int getMin() {        if (smin.empty()) {            return 0;        }        return smin.top();    }private:    stack<int> s;    stack<int> smin;};class MinStackWithOneStack {// Runtime: 28 mspublic:    void push(int x) {        if (s.empty()) {            smin = x;            s.push(0ll);        }        else {            s.push(x - smin);            if (x < smin) {                smin = x;            }        }    }    void pop() {        if (!s.empty()) {            if (s.top() < 0) {                smin = smin - s.top();            }            s.pop();        }    }    int top() {        if (s.empty()) {            return 0;        }        if (s.top() < 0) {            return smin;        }        else {            return s.top() + smin;        }    }    int getMin() {        if (s.empty()) {            return 0;        }        return smin;    }private:    stack<long long> s;    long long smin;};

Max Queue

既然有了 Min Stack,自然可以联想到 Queue。不过我是在 LeetCode 的讨论区发现的。可用于 Sliding Window Maximum

Max Queue 需要借助于双向队列(deque)来实现。

0 0