1.题目
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.
实现一个栈,要求在O(1)时间内得到栈内元素的最小值。
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.
2.分析
剑指offer上也有这一题。做法是使用一个辅助栈–存放每一步栈的操作后当前栈内元素的最小值。
nums—存放栈内元素
mins—存放每个操作后当前栈内最小值
例如:
对于push(x),如果:
x<当前最小值,x压入nums, x压入mins
x>=当前最小值,x压入nums, 当前最小值(mins.top())压入mins
3.代码
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (mins.empty() || x < mins.top())
mins.push(x);
else
mins.push(mins.top());
nums.push(x);
}
void pop() {
nums.pop();
mins.pop();
}
int top() {
return nums.top();
}
int getMin() {
return mins.top();
}
private:
stack<int> nums;//存放栈内元素
stack<int> mins;//存放当前最小值
};