题目:
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.
这道题还算比较简单,虽然刚开始纠结了一下要用什么数据结构来实现,结果一看discussion用stack那我也用stack了。刚开始想着可以直接设置一个min变量,仔细一想万一这个min被pop了咋整,那就只能再设置另外一个stack来存放各种min了。在push时,如果被push进的数字比min小,那么直接往min stack里面push它;在pop时,如果正好是pop最小值,那么相应的也要在min stack里pop掉它。实现起来挺容易的,就是要注意一下,push时的判断条件应该是<=,这个刚开始被坑了好久,因为如果有多个元素重复的话不能只push进一个,否则被pop掉一个出来剩下的就不对了。代码如下,时间28ms,96.81%,空间17.1M,27.2%:
/*
* @lc app=leetcode id=155 lang=cpp
*
* [155] Min Stack
*/
class MinStack {
public:
/** initialize your data structure here. */
stack<int> stk;
stack<int> mins;
MinStack() {
}
void push(int x) {
stk.push(x);
if (mins.empty() || x <= getMin()) {
mins.push(x);
}
}
void pop() {
if (stk.top() == getMin()) {
mins.pop();
}
stk.pop();
}
int top() {
return stk.top();
}
int getMin() {
return mins.top();
}
};
/**
* 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();
*/
另外还有一种只用一个stack的做法,参考:https://leetcode.com/problems/min-stack/discuss/49014/Java-accepted-solution-using-one-stack,先留个坑有空再填……