forked from MaskRay/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
min-stack.cc
58 lines (56 loc) · 1.04 KB
/
min-stack.cc
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
// Min Stack
class MinStack {
public:
MinStack() {}
void push(int x) {
a.push(x);
if (b.empty() || x <= b.top())
b.push(x);
}
void pop() {
if (b.top() == a.top())
b.pop();
a.pop();
}
int top() {
return a.top();
}
int getMin() {
return b.top();
}
private:
stack<int> a, b;
};
// 棧中存儲與當前最小值的差值,可以判斷是否更新了最小值
// 最好使用unsigned,因爲signed類型溢出是未定義的
// 可惜Memory Limit Exceeded
class MinStack {
public:
MinStack() : s(0), d(INT_MAX) {}
void push(int x) {
a.push(x-d);
if (s++ % 32 == 0)
b.push(0);
if (int(x) < int(d)) {
d = x;
b.top() |= 1u << (s-1)%32;
} else
b.top() &= ~ (1u << (s-1)%32);
}
void pop() {
if (b.top() & 1u << (s-1)%32)
d -= a.top();
a.pop();
if (--s % 32 == 0)
b.pop();
}
int top() {
return b.top() & (1u << (s-1)%32) ? d : d+a.top();
}
int getMin() {
return d;
}
private:
stack<unsigned> a, b;
unsigned s, d;
};