返回介绍

Min Stack

发布于 2025-02-22 13:01:34 字数 1313 浏览 0 评论 0 收藏 0

Source

Implement a stack with min() function,
which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

Example
Operations: push(1), pop(), push(2), push(3), min(), push(1), min() Return: 1, 2, 1

Note
min operation will never be called if there is no number in the stack

题解

『最小』栈,要求在栈的基础上实现可以在 O(1)O(1)O(1) 的时间内找出最小值,一般这种 O(1)O(1)O(1) 的实现往往就是哈希表或者哈希表的变体,这里简单起见可以另外克隆一个栈用以跟踪当前栈的最小值。

Java

public class Solution {
  public Solution() {
    stack1 = new Stack<Integer>();
    stack2 = new Stack<Integer>();
  }

  public void push(int number) {
    stack1.push(number);
    if (stack2.empty()) {
      stack2.push(number);
    } else {
      stack2.push(Math.min(number, stack2.peek()));
    }
  }

  public int pop() {
    stack2.pop();
    return stack1.pop();
  }

  public int min() {
    return stack2.peek();
  }

  private Stack<Integer> stack1; // original stack
  private Stack<Integer> stack2; // min stack
}

源码分析

取最小栈的栈顶值时需要先判断是否为空栈(而不仅是 null)。

复杂度分析

均为 O(1)O(1)O(1).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文