forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
86 lines (67 loc) · 1.85 KB
/
main3.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/// Source : https://leetcode.com/problems/max-stack/description/
/// Author : liuyubobobo
/// Time : 2017-11-28
#include <iostream>
#include <map>
#include <cassert>
#include <list>
#include <vector>
using namespace std;
/// Using a list to simulate th stack
/// Using a TreeMap to record every node in the list
/// So we can get the min value in the list quickly and erase it easily
/// Since the problen doesn't require popMin operation,
/// we may not see the advantage of this method,
/// But in problem 716, Max Stack, it's different.
/// https://leetcode.com/problems/max-stack/description/
///
/// Time Complexity: push: O(1)
/// pop: O(1)
/// top: O(1)
/// peekMax: O(1)
/// popMax: O(logn)
/// Space Complexity: O(n)
class MinStack {
private:
list<int> stack;
map<int, vector<list<int>::iterator>> record;
public:
/** initialize your data structure here. */
MinStack() {
stack.clear();
record.clear();
}
void push(int x) {
stack.push_back(x);
list<int>::iterator iter = stack.begin();
advance(iter, stack.size() - 1);
record[x].push_back(iter);
}
int pop() {
int ret = stack.back();
stack.pop_back();
record[ret].pop_back();
if(record[ret].size() == 0)
record.erase(ret);
return ret;
}
int top() {
assert(stack.size() > 0);
return stack.back();
}
int getMin() {
assert(stack.size() > 0);
return record.begin()->first;
}
};
int main() {
MinStack minStack;
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
cout << minStack.getMin() << endl; // -> -3
minStack.pop();
cout << minStack.top() << endl; // -> 0
cout << minStack.getMin() << endl; // -> -2
return 0;
}