155.最小栈

在这里插入图片描述
思路:使用辅助栈存取最小元素

class MinStack:
    def __init__(self):
        self.data = []
        self.helper = []

    def push(self, x):
        self.data.append(x)
        if len(self.helper) == 0 or x <= self.helper[-1]:
            self.helper.append(x)
        else:
            self.helper.append(self.helper[-1])

    def pop(self):
        if self.data:
            self.helper.pop()
            return self.data.pop()

    def top(self):
        if self.data:
            return self.data[-1]

    def getMin(self):
        if self.helper:
            return self.helper[-1]
public class MinStack {
    public Stack<int> x_stack = new Stack<int>();
    public Stack<int> min_stack = new Stack<int>();
    /** initialize your data structure here. */
    public MinStack() 
    {
        min_stack.Push(int.MaxValue);
    }
    
    public void Push(int x) 
    {
        x_stack.Push(x);
        //if(min_stack.Count == 0 || min_stack.Peek() > x)
        //{
            //min_stack.Push(x);
        //}
        min_stack.Push(Math.Min(min_stack.Peek(), x));
    }
    
    public void Pop() 
    {
        
        //if(min_stack.Peek() == x_stack.Peek())
        //{
            //min_stack.Pop();
        //}
        x_stack.Pop();
        min_stack.Pop();
    }
    
    public int Top() 
    {
        return x_stack.Peek();
    }
    
    public int GetMin() 
    {
        return min_stack.Peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.Push(x);
 * obj.Pop();
 * int param_3 = obj.Top();
 * int param_4 = obj.GetMin();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值