来源:Leetcode
原帖:https://oj.leetcode.com/problems/min-stack/
题目:
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.
代码:
原帖:https://oj.leetcode.com/problems/min-stack/
题目:
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.
代码:
class MinStack {
public:
void push(int x) {
s.push(x);
if (min.empty()) {
min.push(x);
} else if (x <= min.top()) {
min.push(x);
}
}
void pop() {
if (s.empty()) {
cerr << "stack is empty" << endl;
}
if (s.top() == min.top()) {
min.pop();
}
s.pop();
}
int top() {
return s.top();
}
int getMin() {
assert(!min.empty());
return min.top();
}
private:
stack<int> s;
stack<int> min;
};
No comments:
Post a Comment