leetcode 155: Min Stack

问题描述:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.

思路:

用的是一个vector来存储数字,而唯一麻烦的getMin。

首先尝试暴力解决,每次getMin都搜索一遍。结果当然是Time Limit Exceeded。

于是将Min当做一个成员存储下来,初始化为INT_MAX,有其他数的情况下INT_MAX不会是最小。

每次push,判断一下是否新加数更小;每次pop,判断一下是否把最小的数pop出去了。于是便大大减少了运行时间。

代码:

class MinStack {  

private:
    vector<int> my_stack;
    int min;
public:
    MinStack() : min(INT_MAX) {}   //intialize to be the max

    void push(int x) {
        my_stack.push_back(x);
        if (x <= min) min = x;      //determine if the new one is minimun
    }

    void pop() {
        if (my_stack.size() == 0) return;
        int lasttop = top();   //record the pop number
        my_stack.pop_back();
        if (my_stack.size() == 0) min = INT_MAX;  
        else
        {
            int size = my_stack.size();

            //if the minimun number is poped, search for the new minimun
            if (min == lasttop)
            {
                min = my_stack[0];
                for (int i = 1; i < size; i++)
                {
                    if (my_stack[i] < min) min = my_stack[i];
                }
            }
        }

    }

    int top() {
        int size = my_stack.size();
        if (size == 0) return -999;
        return my_stack[size - 1];

    }

    int getMin() {
        return min;
    }
};

代码中包含了一些对于空容器的判断情况,只是为了避免程序错误。目测测试样例中并没有造成空容器非法操作的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值