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 };
  • 相关阅读:
    phpHttp请求头
    第八周学习总结
    梦断代码阅读笔记-03
    第七周学习总结
    针对自己开发项目的NABC的认知
    梦断代码阅读笔记
    第六周学习总结
    第五周学习总结
    移动端疫情展示
    第四周学习总结
  • 原文地址:https://www.cnblogs.com/aezero/p/4821691.html
Copyright © 2011-2022 走看看