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

  • 相关阅读:
    行规
    不要在对抽象类接口abstract virtual什么的混淆不清了
    MQ与Webservice的区别
    Asp.net MVC流程简述
    Lambda表达式树
    mysql用户管理、权限管理
    mysql锁、事务、存储引擎、索引
    mysql新增、删除、修改
    mysql基础
    linux的任务计划与mail
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/10466150.html
Copyright © 2011-2022 走看看