-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0155.cpp
129 lines (120 loc) · 2.44 KB
/
0155.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
class MinStack {
private:
const int N = 10;
int *array = NULL;
int capacity = 0;
int size = 0;
int minElem = 0;
public:
// ** initialize your data structure here.
MinStack() {
array = new int[N];
capacity = N;
size = 0;
minElem = 0;
}
void push(int x) {
array[size] = x;
size++;
if (size == 1) {
minElem = x;
} else {
minElem = min(minElem, x);
}
if (size == capacity) {
capacity = 2 * capacity;
int *aux = new int[capacity];
for (int i = 0; i < size; i++) {
aux[i] = array[i];
}
delete[] array;
array = aux;
aux = NULL;
}
}
void pop() {
if (size == capacity / 2) {
capacity /= 2;
int *aux = new int[capacity];
for (int i = 0; i < size; i++) {
aux[i] = array[i];
}
delete[] array;
array = aux;
aux = NULL;
}
size--;
if (size > 0) {
minElem = array[0];
for (int i = 0; i < size; i++) {
minElem = min(minElem, array[i]);
}
}
}
int top() {
if (size > 0) {
return array[size-1];
} else {
// ** dummy, should throw exception
return -1;
}
}
int getMin() {
if (size > 0) {
return minElem;
} else {
return -1;
}
}
};
*/
// ** Referece, Just store difference
class MinStack {
private:
stack<long> myStack;
long minElem;
public:
MinStack() {
myStack = stack<long>();
minElem = 0;
}
void push(int x) {
if (myStack.empty()) {
myStack.push(0);
minElem = x;
} else {
myStack.push(x - minElem);
if (x < minElem) {
minElem = x;
}
}
}
void pop() {
if (myStack.empty()) {
return;
}
long p = myStack.top();
if (p < 0) {
minElem -= p;
}
myStack.pop();
}
int top() {
long p = myStack.top();
if (p > 0) {
return p + minElem;
} else {
return minElem;
}
}
int getMin() { return minElem; }
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/