155. Min Stack

本文介绍了一种特殊的数据结构——最小栈,它能在常数时间内完成压栈、弹栈、获取栈顶元素及检索栈中最小元素的操作。通过两种方法实现:一种是在更新最小值时保存旧值;另一种是使用两个栈,一个存储元素,另一个跟踪最小值。

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

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

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.

要想在常数时间内返回最小值,要么就是用常数变量存储最小值并维护,要么就是用有序的数据结构来确保的最小值的access。

方法一:
这里比较麻烦的就是pop操作如果把最小值删除,如果找到下一个最小值。这里在每次最小值更新的时候就把前一任最小值再存一边,非常巧妙。

class MinStack {
public:
    stack<int> st;
    int minval;
    /** initialize your data structure here. */
    MinStack() {
        minval = INT_MAX;
    }

    void push(int x) {
        if (x <= minval) {
            st.push(minval);
            minval = x;
        }
        st.push(x);
    }

    void pop() {
        if (st.top() == minval) {
            st.pop();
            minval = st.top();
        }
        st.pop();
    }

    int top() {
        return st.top();
    }

    int getMin() {
        return minval;
    }
};

方法二:
用两个栈来维护,一个栈正常存储,一个栈存不断更新的最小值。

class MinStack {
public:
    stack<int> st1;
    stack<int> st2;
    /** initialize your data structure here. */
    MinStack() {

    }

    void push(int x) {
        st1.push(x);
        if (st2.empty() || x <= getMin()) {
            st2.push(x);
        }
    }

    void pop() {
        if (st1.top() == getMin()) {
            st2.pop();
        }
        st1.pop();
    }

    int top() {
        return st1.top();
    }

    int getMin() {
        return st2.top();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值