forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0155-min-stack.cpp
55 lines (45 loc) · 1.09 KB
/
0155-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
/*
Design stack that supports push, pop, top, & retriving min element
2 stacks, 1 normal & 1 monotonic decr, only push if lower than top
Time: O(1)
Space: O(n)
*/
class MinStack {
public:
MinStack() {
}
void push(int val) {
stk.push(val);
if (minStk.empty() || val < minStk.top().first) {
minStk.push({val, 1});
} else if (val == minStk.top().first) {
minStk.top().second++;
}
}
void pop() {
if (stk.top() == minStk.top().first) {
minStk.top().second--;
if (minStk.top().second == 0) {
minStk.pop();
}
}
stk.pop();
}
int top() {
return stk.top();
}
int getMin() {
return minStk.top().first;
}
private:
stack<int> stk;
stack<pair<int, int>> minStk;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/