zoukankan      html  css  js  c++  java
  • leetcode[155] Min Stack

    实现一个堆,可以push,pop,top,和getMin

    主要的应该是getMin,如何找到最小的数。如果每次要找最小的数遍历一边,那貌似没什么意义了。

    做法是,用两个堆,一个用来正常的操作,另一个是记录到当前最小值,如果来一个数字,比最小值的那个对的top还小那就,两个堆都要push,如果pop的时候pop的数和最小值的那个堆的top一样,那就最小值的那个堆也要pop。在getMin的时候,只要返回最小值那个堆的top就可以了。

    稍微模拟一下几个数字进出堆就知道了。

    class MinStack {
    public:
        stack<int> sta, minsta;
        void push(int x) {
            sta.push(x);
            if (minsta.empty() || x <= minsta.top())
                minsta.push(x);
        }
    
        void pop() {
            if (!minsta.empty() && minsta.top() == sta.top())
                minsta.pop();
            sta.pop();
        }
    
        int top() {
            return sta.top();
        }
    
        int getMin() {
            return minsta.top();
        }
    };
  • 相关阅读:
    time fly
    小论文初稿终于完成
    leetcode之Length of Last Word
    static关键字
    参数传递
    this关键字
    面向对象有三大特征
    空指针异常
    变量按数据类型分为
    构造方法
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4172289.html
Copyright © 2011-2022 走看看