【done】剑指offer——面试题21:包含min函数的栈

力扣,https://leetcode.cn/problems/bao-han-minhan-shu-de-zhan-lcof/description/
思路不变,通过栈实现栈

class MinStack {
    public Stack<Integer> s1;
    public Stack<Integer> s2;

    /** initialize your data structure here. */
    public MinStack() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }
    
    public void push(int x) {
        s1.push(x);
        if (s2.isEmpty()) {
            s2.push(x);
        } else {
            int min = Math.min(s2.peek(), x);
            s2.push(min);
        }
    }
    
    public void pop() {
        s1.pop();
        s2.pop();
    }
    
    public int top() {
        return s1.peek();
    }
    
    public int getMin() {
        return s2.peek();
    }
}

Solution1:
辅助栈!
逻辑上要想清楚。。但是用栈结构来实现栈,目的不知为何。。。

class Solution {
public:
    void push(int value) {
        data.push(value);
        if(data_min.empty()){ //辅助栈为空,则value直接压入辅助栈
            data_min.push(value);
        }
        else { //辅助栈非空,
            int stack_min = std::min(data_min.top(),value);
            data_min.push(stack_min);
        }
        return;
    }
    void pop() {
        data.pop();
        data_min.pop();
        return;
    }
    int top() {
        return data.top();
    }
    int min() {
        return data_min.top();
    }
private:
    stack<int> data;
    stack<int> data_min;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值