标签:
Use two stacks :
class MinStack { private: stack<int> s, minS; public: void push(int x) { if (minS.empty() || x <= minS.top()) { minS.push(x); } s.push(x); } void pop() { if (minS.top() == s.top()) { minS.pop(); } s.pop(); } int top() { return s.top(); } int getMin() { return minS.top(); } };
A fancy algorithm, just use one stack and a number. But it will failed with INT_MIN and INT_MAX as overflow.
class MinStack { private: int minValue; stack<int> s; public: void push(int x) { if (s.empty()) { minValue = x; s.push(x); } else if (x < minValue) { s.push(2*x - minValue); minValue = x; } else { s.push(x); } } void pop() { if (s.top() < minValue) { minValue = 2*minValue - s.top(); } s.pop(); } int top() { if (s.top() < minValue) { return 2*minValue - s.top(); } return s.top(); } int getMin() { return minValue; } };
LeetCode – Refresh – Min Stack
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/4355100.html