• 8. Min Stack


    Description:

    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.

      按题意理解,可知这题主要是要实现栈的基本操作,唯一的难点在getMin()函数的实现。该函数的实现可以直接用两个vector容器实现(或者使用两个stack来实现)

      在程序中,我定义了两个vector,一个用于实现栈的基本操作,一个则用于存储当前最小元素

    class MinStack {
      vector<int> a;
      vector<int> min;
    public:
    /** initialize your data structure here. */
    MinStack() {
      min.push_back(2147483647);
    }

    void push(int x) {
      a.push_back(x);
      if(x<min.back()){
        min.push_back(x);
    }
      else{
        min.push_back(min.back());
    }

    }

    void pop() {
      a.pop_back();
      min.pop_back();

    }

    int top() {
      return a.back();
    }

    int getMin() {
      return min.back();
    }
    };

  • 相关阅读:
    spark基础(1)
    Homebrew的使用教程,镜像源的推荐,安装软件的方法
    Scala Trait(特征)
    P5308 [COCI2019] Quiz
    Vjudge contest 425291
    Vjudge contest 424925
    AT3558 Modern Painting
    Vjudge contest 425061
    Vjudge contest 423849
    Codeforces Round 704
  • 原文地址:https://www.cnblogs.com/sarahp/p/6806300.html
Copyright © 2020-2023  润新知