Not very hard to figure out an initial solution, with min heap\monoq\stack. But the key idea is to avoid unnecessary book-keeping when new value is larger than current min value.
class MinStack { public: void push(int x) { stk.push(x); if (minstk.empty() || x <= minstk.top()) // key { minstk.push(x); } } void pop() { if (!stk.empty()) { if (minstk.top() == stk.top()) { minstk.pop(); } stk.pop(); } } int top() { if (!stk.empty()) { return stk.top(); } return -1; } int getMin() { if (!minstk.empty()) { return minstk.top(); } return -1; } private: std::stack<int> stk; std::stack<int> minstk; };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步