zoukankan      html  css  js  c++  java
  • Min Stack leetcode

    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.

    使用一个栈,和一个保存最小值的变量min

    栈中保存的元素是 新加数和当前min的差,然后更新min,使min保持最小

    利用差值使每个栈元素可以包含两个信息量

    class MinStack {
    public:
        void push(int x) {
            if (sta.empty())
            {
                sta.push(0);
                min = x;
            }
            else
            {
                sta.push(x - min);
                if (x < min)
                    min = x;            
            }
        }
    
        void pop() {
            if (sta.empty())
                return;
            long top = sta.top();
            if (top < 0)
                min = min - top;
            sta.pop();
        }
    
        int top() {
            if (sta.empty())
                return 0;
            long top = sta.top();
            if (top < 0)
                return min;
            else
                return min + top;
        }
    
        int getMin() {
            return min;
        }
    private:
        stack<long> sta;
        long min;
    };
  • 相关阅读:
    docker-排除故障
    python的标识符
    python的数据类型
    python的数与字符串
    场景法
    正交试验法
    错误推测法
    决策表法
    因果图法
    python基础--用python执行系统命令
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5097244.html
Copyright © 2011-2022 走看看