20#包含min函数的栈

题意:

实现求最小值 且 操作时间复杂度都是 O(1) 的栈
push(value):将value压入栈中
pop():弹出栈顶元素
top():获取栈顶元素
min():获取栈中最小元素

知识:

Stack<>s=new Stack<Integer>();
s.isEmpty();
s.push(node);
s.peek()
help.pop();

思路:

辅助栈记录入栈顺序中的不递增数字。
即栈顶维护当前最小值。
出栈数字是辅助栈顶数字时,辅助栈顶也需要出栈。
入栈时判断是否等于小于当前最小值

注意

栈为空是不能有peek() pop等操作

import java.util.Stack;

public class Solution {

    Stack<>s=new Stack<Integer>();
    Stack<Integer>help=new Stack<Integer>();
    public void push(int node) {
        if(help.isEmpty()||node<=help.peek()){
            help.push(node);
        }
        s.push(node);
    }

    public void pop() {
        if(s.peek()==help.peek()){
            help.pop();
        }
        s.pop();
    }

    public int top() {
        return s.peek();
    }

    public int min() {
        return help.peek();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值