边push,边记录min
#include <stack> class Solution { public: void push(int value) { stack1.push(value); if (stack2.empty() || stack2.top() > value) stack2.push(value); else stack2.push(stack2.top()); // 当前stack.size的最小元素 } void pop() { stack1.pop(); stack2.pop(); } int top() { return stack1.top(); } int min() { return stack2.top(); } private: stack<int> stack1; stack<int> stack2; // 仅int t不够哦;因为有pop };
直接复制stack,然后比较、pop
#include <stack> class Solution { public: void push(int value) { stack1.push(value); } void pop() { stack1.pop(); } int top() { return stack1.top(); } int min() { stack<int> temp=stack1; int t = temp.top(); temp.pop(); while (!temp.empty()) { t = t < temp.top() ? t : temp.top(); temp.pop(); } return t; } private: stack<int> stack1; };