Leetcode 155: Min Stack

问题描述:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
压栈,移除栈顶,查看栈顶,查找最小 均为O(1)
Implement the MinStack class:

MinStack() initializes the stack object.
void push(val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.

思路一:
一开始我想用两个stack,但是没有想出来。后来看了参考答案,方法是这个样子的,其实我的思路比较接近了。两个栈A和B,如果当前进栈元素小于等于B中栈顶的元素,则A,B均添加这个元素,否则只在A中添加。top()就返回A的栈顶,getMin()就返回B的栈顶。pop()要当心,如果A的栈顶与B的栈顶不同,则直接删除A的栈顶;若相同。则两个栈的栈顶都要被删除。

这个方法的实现不难,若今后有时间再说

我这次尝试用另外一种方法实现,就是栈中的元素不是单纯一个数,而是一个数对,key为这个数的值,value为以这个数为栈顶栈中的最小值。

代码如下:


```java
class MinStack {
    private List<Pair<Integer,Integer>> myList;
    private int top;
    /** initialize your data structure here. */
    public MinStack() {
        myList = new ArrayList<Pair<Integer,Integer>>();
        top = -1;
    }
    
    public void push(int val) {
        top++;
        if (myList.size()==0){
            myList.add(new Pair(val, val));
        }
        else{
            myList.add(new Pair(val, Math.min(val, myList.get(top-1).getValue())));
        }
    }
    
    public void pop() {
        myList.remove(top);
        top--;
    }
    
    public int top() {
        return myList.get(top).getKey();
    }
    
    public int getMin() {
        return myList.get(top).getValue();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值