#12 Min Stack

题目描述:

Implement a stack with min() function, which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

 Notice

min operation will never be called if there is no number in the stack.

Example
push(1)
pop()   // return 1
push(2)
push(3)
min()   // return 2
push(1)
min()   // return 1

题目思路:

这题要求O(1)的时间复杂度。如果我们用一个sorted数据结构,比如map或者set去做,那么每次query的时间为O(logn),不满足题意。如果要达到要求,必须在建立stack的时候,就产生一个min的信息。在这里,我用两个stack在class中:一个stack为正常的stack,一个为min stack。也就是说,min stack在push的时候还是push一个number,但是这个number永远比已经在min stack中的数小:如果top number大于要push的number,min stack就push这个number;反之,就把top number再push一遍。这样,就保证了top number永远是整个stack的最小值。

Mycode(AC = 15ms):

class MinStack {
private:
    stack<int> s;
    stack<int> min_stack;
    
public:
    MinStack() {
        // do initialization if necessary
    }

    void push(int number) {
        // write your code here
        s.push(number);
        if (min_stack.empty() || min_stack.top() >= number) {
            min_stack.push(number);
        }
        else {
            min_stack.push(min_stack.top());
        }
    }

    int pop() {
        // write your code here
        int top = s.top();
        s.pop();
        min_stack.pop();
        return top;
    }

    int min() {
        // write your code here
        return min_stack.top();
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值