zoukankan      html  css  js  c++  java
  • 剑指offer 包含min函数的栈

    题目:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

    注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
     
    代码:
     1 class Solution {
     2 public:
     3     void push(int value) {
     4         st.push(value);
     5         if( smin.empty())
     6             smin.push(value);
     7         else{
     8             if(value <= smin.top()) //若当前值小于等于当前 smin 中栈顶元素则压入栈
     9                 smin.push(value);
    10         }
    11     }
    12     void pop() {
    13         if( !st.empty() ){
    14             if(st.top() == smin.top()) //若出栈元素与 smin 栈顶元素相同,则将其一并出栈
    15                 smin.pop();
    16             st.pop();
    17         }
    18     }
    19     int top() {
    20         if( !st.empty() )
    21             return st.top();
    22     }
    23     int min() {
    24         if( !st.empty() )
    25             return smin.top();
    26     }
    27 private:
    28     stack<int> st;
    29     stack<int> smin; // 用其栈顶指针表示最小元素
    30 };

    我的笔记:根据栈的先进后出原则,可以将当前栈的最小元素直接在另一栈中表示,即同样有先后顺序。

     
     
  • 相关阅读:
    策略模式
    装饰模式
    责任链模式
    算法_快速排序
    算法_二分查找
    数据结构学习笔记_表
    集合遍历remove时ConcurrentModificationException异常
    LinkedHashMap笔记
    Windows相关命令
    高效率幂运算
  • 原文地址:https://www.cnblogs.com/john1015/p/12956428.html
Copyright © 2011-2022 走看看