Min Stack
Total Accepted: 72994
Total Submissions: 326015
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.
Subscribe to see which companies asked this question
Hide Similar Problems
思路:
使用两个栈:一个实践数据存储栈S,一个存储最小数的栈minS。
1.x入栈时:
1)x直接入S栈;
2)minS栈为空时,x直接入minS栈;minS栈不为空时,将x和minS栈比较,较小值入minS栈;
这样minS栈栈顶始终维持的是S栈中的最小值,因此取最小值的时间复杂度为O(1)。
2.x出栈时:S和minS都直接出栈。
c++ coce:
class MinStack {
public:
void push(int x) {
S.push(x);
if(!minS.empty())
x = x < minS.top()? x:minS.top();
minS.push(x);
}
void pop() {
if(!S.empty()) S.pop();
minS.pop();
}
int top() {
return S.top();
}
int getMin() {
return minS.top();
}
private:
stack<int> S,minS;
};