设计一个支持 push
,pop
,top
操作,并能在常数时间内检索到最小元素的栈。
push(x)
—— 将元素 x 推入栈中。
pop()
—— 删除栈顶的元素。
top()
—— 获取栈顶元素。
getMin()
—— 检索栈中的最小元素。
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
双栈即可
- 数据栈与最小栈
let MinStack = function() {
this.dataStack = [];
this.minStack = [];
this.min = Infinity;
}
MinStack.prototype.push = function(x) {
this.dataStack.push(x);
this.min = Math.min(this.min, x);
this.minStack.push(this.min);
}
MinStack.prototype.pop = function() {
this.dataStack.pop();
this.minStack.pop();
this.min = this.minStack.length === 0 ? Infinity : this.minStack[this.minStack.length - 1];
}
MinStack.prototype.top = function() {
return this.dataStack[this.dataStack.length - 1];
}
MinStack.prototype.getMin = function() {
return this.min;
}
var test = new MinStack();
test.push(2);
test.push(1);
test.push(3);
// test.pop();
console.log(test.getMin());
console.log(test.top());
const (
INT_MAX = int(^uint((0)) >> 1)
INT_MIN = ^INT_MAX
)
var min = INT_MAX
var s1 = []int{}
var s2 = []int{}
func push(x int) {
s1 = append(s1, x)
min = Min(min, x)
s2 = append(s2, min)
}
func pop() {
s1 = s1[:len(s1) - 1]
s2 = s2[:len(s2) - 1]
if len(s2) == 0 {
min = INT_MAX
} else {
min = s2[len(s2) - 1]
}
}
func top() int {
return s1[len(s1) - 1]
}
func getMin() int {
return min
}
class MinStack {
private Stack<Integer> dataStack;
private Stack<Integer> minStack;
private int min;
/** initialize your data structure here. */
public MinStack() {
dataStack = new Stack<>();
minStack = new Stack<>();
min = Integer.MAX_VALUE;
}
public void push(int x) {
dataStack.push(x);
min = Math.min(min, x);
minStack.push(min);
}
public void pop() {
dataStack.pop();
minStack.pop();
min = minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek();
}
public int top() {
return dataStack.peek();
}
public int getMin() {
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/