155. Min Stack

problem

solution

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
class MinStack {
private:
stack<int> sta, minsta;

public:
MinStack() {

}

void push(int val) {
sta.push(val);
// 單調遞減stack
if(minsta.empty()) minsta.push(val);
else if(!minsta.empty() && minsta.top()>=val ) minsta.push(val);
}

void pop() {
int t = sta.top(); sta.pop();
if(t == minsta.top()) minsta.pop();

}

int top() {
return sta.top();
}

int getMin() {
return minsta.top();
}
};