zoukankan      html  css  js  c++  java
  • 【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.

    提示:

    这道题可以通过使用两个stack实现对最小值的记录,每次push进来一个数后,比较该数是否小于当前最小值,如果小于的话就push进保存最小值的stack当中,由于stack“先进后出”的特性,因此后面Push进来的较大的值并不会影响最小值的判断,因为这个较大的值会在之前push进来的较小的值之前pop出去。

    另外还可以只使用一个stack,具体的方法就是在stack中存放pair,每个pair的first存放的是值,second存放的是若当前pair在顶部状态时的最小值。

    代码:

    2stack:

    class MinStack {
        stack<int> s;
        stack<int> min;
    public:
        void push(int x) {
            if (min.empty() || x <= getMin()) min.push(x);
            s.push(x);
        }
    
        void pop() {
            if (s.top() == min.top()) min.pop();
            s.pop();
        }
    
        int top() {
            return s.top();
        }
    
        int getMin() {
            return min.top();
        }
    };

     1stack:

    class MinStack {
        typedef pair<int,int> pairt;
        deque<pairt> stack;
    public:
        void push(int x) {
            if (stack.size())
                stack.push_back(make_pair(x, min(x,getMin())));
            else 
                stack.push_back(make_pair(x, x));
        }
    
        void pop() {
            stack.pop_back();
        }
    
        int top() {
            return stack.back().first;
        }
    
        int getMin() {
            return stack.back().second;
        }
    };
  • 相关阅读:
    常用正则表达式
    偶得
    监控文件夹里面文件修改的小程序
    使用Windows服务发布WCF服务
    查看wcf服务中方法测试客户端
    twitter注册使用指南
    打包工具使用下载
    c#多线程编程
    请确保此文件可访问并且是一个有效的程序集或COM组件
    添加Service Reference, 无法为服务生成代码错误的解决办法
  • 原文地址:https://www.cnblogs.com/jdneo/p/4794516.html
Copyright © 2011-2022 走看看