• 剑指 Offer 30. 包含min函数的栈


    剑指 Offer 30. 包含min函数的栈

    定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

    示例:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.min(); --> 返回 -3.
    minStack.pop();
    minStack.top(); --> 返回 0.
    minStack.min(); --> 返回 -2.

    提示:

    各函数的调用总次数不超过 20000 次

    点击查看代码
    package 剑指offer二刷;
    
    import java.util.Stack;
    
    /**
     * @author :szq
     * @date :Created in 2022/3/18 10:15
     * @description:剑指 Offer 30. 包含min函数的栈
     * @modified By:
     * @version: $
     */
    class  包含min函数的栈 {
        class MinStack {
    
            /**
             * initialize your data structure here.
             */
            Stack<Integer> s1 = new Stack<Integer>();
            Stack<Integer> s2 = new Stack<Integer>();
    
            public MinStack() {
    
            }
    
            public void push(int x) {
                s1.push(x);
                if (!s2.empty()) {  //如果第二个辅助栈不为空,则比较辅助栈的栈顶元素和刚准备进入元素的大小。
    //                if (s2.peek() < x)
    //                    s2.push(s2.peek());
    //                else
    //                    s2.push(x);  //那个小入哪个
    
                    //三元表达式
    
                    s2.push(s2.peek()>x?x:s2.peek());
                } else
                    s2.push(x);
    
    
            }
    
            public void pop() {
    
                s1.pop();
                s2.pop();
    
            }
    
            public int top() {
    
                return s1.peek();
    
            }
    
            public int min() {
                return s2.peek();
            }
        }
    }
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.min();
     */
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.min();
     */
    
  • 相关阅读:
    spring异常
    springboot+mybatis
    mybatis初识
    模板引擎Dot
    mysql数据库操作
    1. 安装Oracle,配置环境 2. 实现查询From子句 3. 实现查询where子句 4. 实现查询order by子句
    (1)Set集合 (2)Map集合 (3)异常机制
    (1)网络编程的常识 (2)基于tcp协议的编程模型 (3)tcp协议和udp协议的比较 (4)基于udp协议的编程模型
    (1)线程的常用方法 (2)线程的同步机制 (3)网络编程的常识
    (1)I/O流 (2)线程
  • 原文地址:https://www.cnblogs.com/shenxiaodou/p/16025474.html
Copyright © 2020-2023  润新知