zoukankan      html  css  js  c++  java
  • LeetCode(155)题解--Min Stack

    https://leetcode.com/problems/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.

    思路:

    关键在于找最小值要O(1)复杂度,所以空间换时间。一个额外的vector存储递减序入栈的数字。

    AC代码:

     1 class MinStack {
     2 public:
     3     MinStack(){ st_min.push_back(INT_MAX); };
     4     void push(int x) {
     5         if (x <= st_min[st_min.size()-1])
     6             st_min.push_back(x);
     7         st.push_back(x);
     8         return;
     9     }
    10 
    11     void pop() {
    12         if (st[st.size() - 1] == st_min[st_min.size() - 1]){
    13             st_min.pop_back();
    14         }
    15         st.pop_back();
    16         return;
    17     }
    18 
    19     int top() {
    20         return st[st.size() - 1];
    21     }
    22 
    23     int getMin() {
    24         return st_min[st_min.size() - 1];
    25     }
    26 
    27 private:
    28     vector<int> st;
    29     vector<int> st_min;
    30 };
  • 相关阅读:
    3.1按钮
    2.1线性布局
    2.2相对布局
    1.4Activity保存现场状态
    1.1Activity跳转与传值
    1.2Activity返回值
    1.3Activity生命周期
    WebSocket
    Jms消费者模式
    课堂实践5-31
  • 原文地址:https://www.cnblogs.com/aezero/p/4821691.html
Copyright © 2011-2022 走看看