leetcode链接
害, 我以为题目是要求自己实现一个栈,可是看了题解人家都是用现有的栈来操作的。。。
关键在于常数时间内检索栈中的最小元素,显然是不能遍历栈了。应该是需要在push的时候对栈的最小值进行存储,pop的时候也需要对最小值进行更新,那常见的思路就是再维护一个容器存储对应的最小值了,这个容器选择很多,最好用栈(因为仅仅需要push和pop操作就可以啦!)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class MinStack { public: /** initialize your data structure here. */ MinStack() { } void push(int x) { if(stk1.empty()){ stk1.push(x); stk2.push(x); }else{ stk1.push(x); stk2.push(min(x, stk2.top())); } } void pop() { stk1.pop(); stk2.pop(); } int top() { return stk1.top(); } int getMin() { return stk2.top(); } private: stack<int> stk1; stack<int> stk2; // 存储最小值 }; |
其实可以一个栈就实现,栈里的元素为pair
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class MinStack { public: /** initialize your data structure here. */ MinStack() { } void push(int x) { if(stk.empty()){ stk.push({x, x}); }else{ stk.push({x, min(x, stk.top().second)}); } } void pop() { stk.pop(); } int top() { return stk.top().first; } int getMin() { return stk.top().second; } private: stack<pair<int, int>> stk; }; |