LeetCode – Refresh – Min Stack
2015-03-21 07:35
267 查看
Use two stacks :
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: 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 – Best Time to Buy and Sell Stock ii
- LeetCode – Refresh – Flatten Binary Tree To Linked List
- LeetCode – Refresh – Interleaving String
- LeetCode – Refresh – Longest Substring Without Repeating Characters
- LeetCode – Refresh – Maximum Gap
- LeetCode – Refresh – Next Permutation
- Leetcode: Min Stack
- [leetcode]Min Stack
- LeetCode – Refresh – Populating Next Right Pointers in Each Node I and II
- LeetCode – Refresh – Remove Duplicates from Sorted List II
- LeetCode – Refresh – Sqrt(x)
- [leetcode] #155 Min Stack
- [LeetCode]Min Stack
- Min Stack--LeetCode
- LeetCode155:Min Stack
- 【Leetcode】Min Stack
- LeetCode - E- Min Stack
- LeetCode – Refresh – Best Time to Buy and Sell Stock iii
- LeetCode – Refresh – Clone Graph
- LeetCode – Refresh – Dungeon Game