zoukankan      html  css  js  c++  java
  • O(1)时间复杂度求栈中最小元素

     1 import java.util.Stack;
     2 
     3 /**
     4  * 功能:O(1)时间复杂度求栈中最小元素
     5  * 思路:空间换取时间,使用两个栈,stack1栈存储数据,stack2栈存储最小值;
     6  * stack1入栈时,发现比stack2栈顶元素还小,则同时入stack2;stack1出栈时,同时也将stack2中的元素出栈。
     7  */
     8 public class Main {
     9 
    10     private Stack<Integer> stackValue = new Stack<Integer>();
    11     private Stack<Integer> stackMin = new Stack<Integer>();
    12 
    13     /**
    14      * @param integer
    15      */
    16     public void push(Integer integer) {
    17         stackValue.push(integer);
    18         if (integer < getMin()) {
    19             stackMin.push(integer);
    20         }
    21     }
    22 
    23     /**
    24      * @return
    25      */
    26     public Integer pop() {
    27         if (stackValue.peek() == stackMin.peek()) {
    28             stackMin.pop();
    29         }
    30         return stackValue.pop();
    31     }
    32 
    33     /**
    34      * @return
    35      */
    36     public Integer getMin() {
    37         if (stackMin.size() == 0) {
    38             return Integer.MAX_VALUE;
    39         }
    40 
    41         return stackMin.peek();
    42     }
    43 
    44     public static void main(String[] args) {
    45 
    46         Main main = new Main();
    47 
    48         main.push(10);
    49         main.push(20);
    50         main.push(9);
    51         main.push(15);
    52 
    53         System.out.println(main.getMin());
    54     }
    55 }
  • 相关阅读:
    团队冲刺2.7
    单词接龙
    团队冲刺2.6
    梦断代码阅读笔记02
    团队冲刺2.5
    吾日三省吾身(6)
    吾日三省吾身(5)
    周计划01(20200921-20200927)
    吾日三省吾身(4)
    吾日三省吾身(3)
  • 原文地址:https://www.cnblogs.com/jiangyi-uestc/p/9236340.html
Copyright © 2011-2022 走看看