LeetCode 155. Min Stack
Description
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:
|
|
Solution
用一个普通的栈完成栈的一般功能。另外用一个栈维护一个递减数列。
递减栈的目的是保证该栈的栈顶即是普通栈中所有数的最小值。因此递减栈维护的规则是:
1.普通栈push时若递减栈为空,进栈。(体现为只有一个数时该数即是最小值)
2.普通栈push时若新的数元素小于等于递减栈的栈顶,进栈。(体现为有更小的值加入)
3.普通栈pop时如果出栈的数与递减栈的栈顶相等,递减栈也出栈一个数。(体现为最小的数已经出栈,递减栈的栈顶变成了次小值)
Code
|
|