标签:最小 shell new ret const 思路 time opera ons
Problem:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
思路:
定义一个栈与保存最小值的栈。最小值栈与栈同时push和pop,添加值的时候,与最小值栈顶元素比较,若新值小则将新值压入最小值栈,否则将最小值栈顶的元素再次压栈。
Solution (C++):
stack<int> stk, min_stk;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
stk.push(x);
if (min_stk.empty() || x < min_stk.top())
min_stk.push(x);
else min_stk.push(min_stk.top());
}
void pop() {
if (!stk.empty() && !min_stk.empty()) {
stk.pop();
min_stk.pop();
}
}
int top() {
if (stk.empty()) return -1;
return stk.top();
}
int getMin() {
if (min_stk.empty()) return -1;
return min_stk.top();
}
性能:
Runtime: 40 ms??Memory Usage: 14.5 MB
思路:
Solution (C++):
性能:
Runtime: ms??Memory Usage: MB
标签:最小 shell new ret const 思路 time opera ons
原文地址:https://www.cnblogs.com/dysjtu1995/p/12748844.html