Description
Difficulty: Easy
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:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); –> Returns -3.
minStack.pop();
minStack.top(); –> Returns 0.
minStack.getMin(); –> Returns -2.
题意:
自己实现一个栈,除了推、弹、查看栈顶以外还要求常数时间找到栈中最小值。
Solution
基本思路是使用 list 结构,自带 push(append)与 pop 方法。top 只需要返回最后一个元素。
对于最小值,最单纯的思路是用自带方法返回 min(list),但是时间复杂度不允许。
因此维护一个最小值 stack,在每次 push 的时顺便在最小值 stack 中 push 当前最小值(包括输入值),每次 pop 时最小值栈也随之 pop。需要获取最小值时只需要获取最小值 stack 的最后一个元素即可。
|
|





近期评论