-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0155. Min Stack.cpp
More file actions
49 lines (40 loc) · 921 Bytes
/
0155. Min Stack.cpp
File metadata and controls
49 lines (40 loc) · 921 Bytes
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
// Task: https://leetcode.com/problems/min-stack/
#include<iostream>
#include<vector>
class MinStack {
public:
std::vector<long long> st;
long long minElem = INT_MAX;
MinStack() {
}
void push(int val) {
st.push_back(val);
minElem = val < minElem ? val : minElem;
}
void pop() {
if (st.back() == getMin()) {
st.pop_back();
minElem = st.empty() ? INT_MAX : *std::min_element(st.begin(), st.end());
}
else {
st.pop_back();
}
}
int top() {
return st.back();
}
int getMin() {
return minElem;
}
};
int main() {
MinStack *minStack = new MinStack();
minStack->push(-2);
minStack->push(0);
minStack->push(-3);
minStack->getMin(); // return -3
minStack->pop();
minStack->top(); // return 0
minStack->getMin(); // return -2
return 0;
}