zoukankan      html  css  js  c++  java
  • Min Stack 解答

    Question

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • getMin() -- Retrieve the minimum element in the stack.

    Solution

    Original thinking is to use two stacks, one to store input elements, and the other is to store current min value.

    However, there is an improvement that only use one stack.

    This stack is to store diff between input value and current min value.

    if current value < min value, we set min as current imput value.

    Therefore, when we pop or peek each element in stack, we know:

    If it's greater than 0, then it must be greater than current min value.

    If it's smaller than 0, then it must equal to current min value.

     1 class MinStack {
     2     Stack<Long> diff;
     3     private long min;
     4     
     5     public MinStack() {
     6         min = Integer.MAX_VALUE;
     7         diff = new Stack<Long>();
     8     }
     9     public void push(int x) {
    10         diff.push((long)x - min);
    11         min = x < min? x : min;
    12     }
    13     public void pop() {
    14         if (diff.size() < 1)
    15             return;
    16         long tmp = diff.pop();
    17         if (tmp < 0)
    18             min -= tmp;
    19     }
    20     public int top() {
    21         long tmp = diff.peek();
    22         if (tmp < 0)
    23             tmp = min;
    24         else
    25             tmp += min;
    26         return (int)tmp;
    27     }
    28     public int getMin() {
    29         return (int)min;
    30     }
    31 }

     注意这里stack和min的类型都应该是long,否则会有越界问题!

  • 相关阅读:
    记一份电网信息化建设企业信息分析平台规划
    2018年个人心灵历程记录
    OGG For Bigdata To Kafka同步问题处理
    Vue.js有赞商城(思路以及总结整理)
    汉诺塔-递归算法
    git合并分支
    js实现页面消息滚动效果
    chrome实现网页高清截屏(F12、shift+ctrl+p、capture)
    JS计算时间差
    Socket.io详解
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4860010.html
Copyright © 2011-2022 走看看