• 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.

     

    Example:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> Returns -3.
    minStack.pop();
    minStack.top();      --> Returns 0.
    minStack.getMin();   --> Returns -2.

    要完成的函数:

    class MinStack {
    public:

      MinStack()

      void push(int x)

      void pop() 

      int top() 

      int getMin()

    }

    说明:

    1、这道题目让我们设计一个栈,支持常规的入栈、出栈、读出栈顶元素的操作,同时支持时间复杂度为O(1)的读出栈内最小元素的操作。

    2、原本要定义一个数组,但是数组自己动态定义比较麻烦,于是偷懒,使用了vector来实现。

    3、时间复杂度有限制,最容易想到的解决办法就是增加空间复杂度,多定义一个vector来使用。解决问题。

    代码:(本代码不支持空栈的栈顶元素读出和空栈的元素出栈,以及空栈的读出最小元素,只是一个简易的代码)

    class MinStack {
    public:
        vector<int>array;
        vector<int>min;
        MinStack() 
        {
            min.push_back(INT_MAX);
        }
        
        void push(int x)
        {
            if(x<min.back())
                min.push_back(x);
            else
                min.push_back(min.back());
            array.push_back(x);
        }
        
        void pop() 
        {
            array.pop_back();
            min.pop_back();
        }
        
        int top() 
        {
            return array.back();
        }
        
        int getMin() 
        {
            return min.back();
        }
    };
  • 相关阅读:
    ZOJ3513_Human or Pig
    ZOJ2083_Win the Game
    ZOJ2725_Digital Deletions
    ZOJ2686_Cycle Gameu
    UVALive
    ZOJ2290_Game
    ZOJ3067_Nim
    P3159 [CQOI2012]交换棋子(费用流)
    P3153 [CQOI2009]跳舞(最大流多重匹配)
    P3121 [USACO15FEB]审查(黄金)Censoring (Gold)(ac自动机)
  • 原文地址:https://www.cnblogs.com/chenjx85/p/8763239.html
Copyright © 2020-2023  润新知