Min Stack

https://leetcode.com/problems/min-stack/description/

Question

LintCode

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.

Notice

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

Example

push(1)
pop()   // return 1
push(2)
push(3)
min()   // return 2
push(1)
min()   // return 1

LeetCode

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.

Example:

Analysis

Using Two Stacks

利用两个栈结构,其中一个是主要的正常stack,满足pop(), push()的O(1)时间要求,另外一个作为辅助的minStack,仅存入min的integer。 min = Integer.parseInt(minStack.peek().toString());

push()时,如果number <= min,则push到minStack上 pop()时,如果number == min,也从minStack上pop

题中的例子,最终stack为[2, 3, 1], minStack为 [2, 1]

这样minStack中保留stack中最小元素相对顺序,在pop之后依然能够保证minStack的栈顶为当前最小元素。

Using LinkedList Node

自定义Node类,其中包含该节点对应的min,这样就可以实现O(1)的getMin()操作,其余push(), pop(),也因为LinkedList实现O(1)

Using Single Stack

这个想法较为奇特一些,就是在stack中存入当前入栈的值与最小值之差,x - min

优点是getMin() 操作只需返回min即可,但是push(), pop() 操作需要结合min以及栈顶元素

缺点是:

The problem for the solution is the cast. Since the possible gap between the current value and the min value could be Integer.MAX_VALUE-Integer.MIN_VALUE;

Solution

Using Two Stacks*

注意:这里有一个trick要注意,因为stack中存入的是Integer,因此 pop()时,检查是否minStack和stack中的元素是否相等时,需要做强制转化为(int) 变量,否则会出现错误(当元素范围在-128 ~ 127之外时):

https://stackoverflow.com/questions/3637936/java-integer-equals-vs

The JVM is caching Integer values. == only works for numbers between -128 and 127

http://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

You can't compare twoIntegerwith a simple == they're objects so most of the time references won't be the same.

There is a trick, with Integer between -128 and 127, references will be the same as autoboxing usesInteger.valueOf()which caches small integers.

因此,可以先用int强制转化。

参考:

--

Time: O(1)

Space: O(n)

Using One Stack - store difference between x and min

  • Time: O(1)

  • Space: O(1)

top() - 如果当前栈顶的对应元素是新的min值,那么 top() 对应 min, 否则对应 stack.peek() + min

push() - 每次存入

Using One Stack with Custom Element Class Object - Store min within each element

Time: O(1)

Space: O(n), extra space for the min value in the custom class object

Using LinkedList Node*

Reference

https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/

Last updated

Was this helpful?