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 }
  • 相关阅读:
    刷新页面的问题
    JS属性
    1-4_基本概念_进程间通信及同步
    1-3_基本概念_程序&进程
    1-2_基本概念_用户和组&目录、链接及文件
    1-1_基本概念_内核&shell
    d 操作系统概述
    对比生成测试算法用例
    简单的排序算法:冒泡排序法
    简单的排序算法:插入排序法
  • 原文地址:https://www.cnblogs.com/jiangyi-uestc/p/9236340.html
Copyright © 2011-2022 走看看