zoukankan      html  css  js  c++  java
  • [LeetCode] 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.
    Hide Tags
     Stack Data Structure
     

      这个是通过两个stack 维护,一个辅助栈support 维护非升序的情况,注意需要非升序,一个是用于全部data 维护。
     
    #include <iostream>
    #include <stack>
    using namespace std;
    
    class MinStack {
    public:
        stack<int> data;
        stack<int> support;
    
        void push(int x) {
            if(data.empty()){
                data.push(x);
                support.push(x);
            }
            else{
                data.push(x);
                if(x<=support.top()) support.push(x);
            }
        }
    
        void pop() {
            if(data.top()==support.top())   support.pop();
            data.pop();
        }
    
        int top() {
            return data.top();
        }
    
        int getMin() {
            return support.top();
        }
    };
    int main()
    {
        MinStack myMinStack;
        myMinStack.push(1);
        cout<<myMinStack.getMin()<<endl;
        myMinStack.push(2);
        cout<<myMinStack.getMin()<<endl;
        myMinStack.push(0);
        cout<<myMinStack.getMin()<<endl;
        myMinStack.pop();
        myMinStack.pop();
        cout<<myMinStack.getMin()<<endl;
        myMinStack.pop();
        return 0;
    }
  • 相关阅读:
    EBS系统请求表定时清除
    excel 单元格公式实现like
    延迟加载
    JS中的面向对象
    JavaScript中的事件机制
    原型与继承机制
    WinForm中的简单打印
    图片预加载
    客户端存储
    JS中一些重要概念
  • 原文地址:https://www.cnblogs.com/Azhu/p/4324442.html
Copyright © 2011-2022 走看看