题解 | #包含min函数的栈#
包含min函数的栈
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
class Solution {
public:
void push(int value) {
// temp.push(value);
s.push(value);
}
void pop() {
// temp.pop();
s.pop();
}
int top() {
return s.top();
}
int min() {
if (s.empty()) {
return {};
}
int x = 10001;
while (!s.empty()) {
if (x > s.top()) x = s.top();
temp.push(s.top());
s.pop();
}
while (!temp.empty()) {
s.push(temp.top());
temp.pop();
}
return x;
}
private:
stack<int> s;
stack<int> temp;
};
最小值,只需要每次查找当前栈中的最小值,遍历出栈找到最小值,但是需要还原栈。利用一个辅助栈实现。
查看7道真题和解析