zoukankan      html  css  js  c++  java
  • LeetCode--155--最小栈(java版)

    设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

    • push(x) -- 将元素 x 推入栈中。
    • pop() -- 删除栈顶的元素。
    • top() -- 获取栈顶元素。
    • getMin() -- 检索栈中的最小元素。

    示例:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> 返回 -3.
    minStack.pop();
    minStack.top();      --> 返回 0.
    minStack.getMin();   --> 返回 -2.
     1 class MinStack {
     2     private Stack<Integer> stack1;
     3     private Stack<Integer> stack2;
     4     /** initialize your data structure here. */
     5     public  MinStack() {
     6         this.stack1 = new Stack<Integer>();
     7         this.stack2 = new Stack<Integer>();
     8     }
     9     
    10     public void push(int x) {
    11         this.stack1.push(x);
    12         if(this.stack2.isEmpty()){
    13             this.stack2.push(x);
    14         }else if(x < this.stack2.peek()){
    15             this.stack2.push(x);
    16         }else{
    17             this.stack2.push(stack2.peek());
    18         }
    19     }
    20     
    21     public void pop() {
    22             this.stack1.pop();
    23             this.stack2.pop(); 
    24     }
    25     
    26     public int top() {
    27             return this.stack1.peek();
    28     }
    29     
    30     public int getMin() {
    31         return this.stack2.peek();
    32         }
    33     }
    34 
    35 /**
    36  * Your MinStack object will be instantiated and called as such:
    37  * MinStack obj = new MinStack();
    38  * obj.push(x);
    39  * obj.pop();
    40  * int param_3 = obj.top();
    41  * int param_4 = obj.getMin();
    42  */

    2019-03-03 16:21:27

  • 相关阅读:
    复习 层叠样式表
    asp后台练习总结
    序列化
    WindowsForm 增 删 查 改
    WindowsForm 计算器
    UML建模和开发预演
    rabbitmq 使用心得
    设计模式之策略模式
    单一职责原则
    设计模式之工厂模式
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/10466150.html
Copyright © 2011-2022 走看看