forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 15
/
min-stack.cpp
77 lines (66 loc) · 1.69 KB
/
min-stack.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
// Time: O(n)
// Space: O(1)
class MinStack {
public:
void push(int number) {
if (elements_.empty()) {
elements_.emplace(0);
stack_min_ = number;
} else {
elements_.emplace(static_cast<int64_t>(number) - stack_min_);
if (number < stack_min_) {
stack_min_ = number; // Update min.
}
}
}
void pop() {
auto diff = elements_.top();
elements_.pop();
if (diff < 0) {
stack_min_ -= diff; // Restore previous min.
}
}
int top() {
if (elements_.top() > 0) {
return stack_min_ + elements_.top();
} else {
return stack_min_;
}
}
int getMin() {
return stack_min_;
}
private:
stack<int64_t> elements_;
int stack_min_;
};
// Time: O(n)
// Space: O(n)
class MinStack2 {
public:
void push(int number) {
if (cached_min_with_count_.empty() || cached_min_with_count_.top().first > number) {
cached_min_with_count_.emplace(number, 1);
} else if (cached_min_with_count_.top().first == number) {
++cached_min_with_count_.top().second;
}
elements_.emplace(number);
}
void pop() {
if (cached_min_with_count_.top().first == elements_.top()) {
if (--cached_min_with_count_.top().second == 0) {
cached_min_with_count_.pop();
}
}
elements_.pop();
}
int top() {
return elements_.top();
}
int getMin() {
return cached_min_with_count_.top().first;
}
private:
stack<int> elements_;
stack<pair<int, int>> cached_min_with_count_;
};