-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0155_MinStack.cpp
More file actions
53 lines (44 loc) · 1.1 KB
/
Copy path0155_MinStack.cpp
File metadata and controls
53 lines (44 loc) · 1.1 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
#include <iostream>
#include <stack>
using namespace std;
class MinStack
{
// keep track of the current inserted val and min value in the stack
std::stack<std::pair<int, int>> s;
public:
MinStack() = default;
void push(const int val)
{
if (s.empty()) {
s.emplace(val, val);
} else {
if (val < s.top().second) {
s.emplace(val, val);
} else {
s.emplace(val, s.top().second);
}
}
}
void pop() { s.pop(); }
int top() const { return s.top().first; }
int getMin() const { return s.top().second; }
};
/**
* 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();
*/
int main()
{
MinStack minStack{};
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
cout << minStack.getMin() << endl; // return -3
minStack.pop();
cout << minStack.top() << endl; // return 0
cout << minStack.getMin() << endl; // return -2
}