題目: LeetCode - 155. Min Stack
題目說明
設計一個 Stack,並完成部分功能。
解題思路
可以直接使用 STL 的容器,所以只須明白 Stack 的運作模式即可。
參考解法
解法一:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | class MinStack {public:
 
 vector<int> minstack;
 
 MinStack() {
 ios_base::sync_with_stdio(false);
 cin.tie(0);
 }
 
 void push(int x) {
 minstack.push_back(x);
 }
 
 void pop() {
 minstack.pop_back();
 }
 
 int top() {
 return minstack.back();
 }
 
 int getMin() {
 return *(min_element(minstack.begin(), minstack.end()));
 }
 };
 
 | 
解法二:
| 12
 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
 
 | class MinStack {public:
 
 stack<pair<int, int>> minstack;
 
 MinStack() {
 ios_base::sync_with_stdio(false);
 cin.tie(0);
 }
 
 void push(int x) {
 if(minstack.empty() || minstack.top().second >= x)
 minstack.push({x, x});
 else
 minstack.push({x, minstack.top().second});
 }
 
 void pop() {
 minstack.pop();
 }
 
 int top() {
 return minstack.top().first;
 }
 
 int getMin() {
 return minstack.top().second;
 }
 };
 
 | 
2020-08-18 重寫
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | static auto __ = []()
 {
 std::ios_base::sync_with_stdio(false);
 std::cin.tie(nullptr);
 std::cout.tie(nullptr);
 return 0;
 }();
 class MinStack {
 public:
 
 MinStack() {}
 
 void push(int x) {
 if(s.empty()) { s.emplace(x, x); return; }
 s.emplace(x, x < s.top().second ? x : s.top().second);
 }
 
 void pop() { s.pop(); }
 
 int top() { return s.top().first; }
 
 int getMin() { return s.top().second; }
 private:
 stack<pair<int, int>> s;
 };
 
 |