-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxStack.cpp
More file actions
89 lines (75 loc) · 1.62 KB
/
MaxStack.cpp
File metadata and controls
89 lines (75 loc) · 1.62 KB
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
87
88
89
// Double Stack
class MaxStack {
public:
/** initialize your data structure here. */
MaxStack() {}
void push(int x) {
if (s2.empty() || s2.top() <= x) s2.push(x);
s1.push(x);
}
int pop() {
if (!s2.empty() && s2.top() == s1.top()) s2.pop();
int t = s1.top();
s1.pop();
return t;
}
int top() {
return s1.top();
}
int peekMax() {
return s2.top();
}
int popMax() {
int mx = s2.top();
stack<int> t;
while (s1.top() != s2.top()) {
t.push(s1.top());
s1.pop();
}
s1.pop();
s2.pop();
while (!t.empty()) {
push(t.top());
t.pop();
}
return mx;
}
private:
stack<int> s1, s2;
};
// list + hashmap
#include <list>
class MaxStack {
public:
/** initialize your data structure here. */
MaxStack() {}
void push(int x) {
v.insert(v.begin(), x);
m[x].push_back(v.begin());
}
int pop() {
int x = *v.begin();
m[x].pop_back();
if (m[x].empty()) m.erase(x);
v.erase(v.begin());
return x;
}
int top() {
return *v.begin();
}
int peekMax() {
return m.rbegin()->first;
}
int popMax() {
int x = m.rbegin()->first;
auto it = m[x].back();
m[x].pop_back();
if (m[x].empty()) m.erase(x);
v.erase(it);
return x;
}
private:
list<int> v;
map<int, vector<list<int>::iterator>> m;
};
// https://www.cnblogs.com/grandyang/p/7823424.html