Question : Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) — Push element x onto stack.
pop() — Removes the element on top of the stack.
top() — Get the top element.
getMin() — Retrieve the minimum element in the stack.
Best 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
31
32
33
34
35
36
37
publicclassMinStackBest{
Stack<Long> stack;
long min = 0;
publicMinStackBest() {
stack = new Stack<Long>();
}
publicvoidpush(int x) {
if (stack.isEmpty()) {
stack.push(0L);
min = x;
} else {
stack.push(x - min);
if (x < min) {
min = x;
}
}
}
publicvoidpop() {
if (stack.isEmpty()) {
return;
}
long pop = stack.pop();
if (pop < 0) {
min = min - pop;
}
}
publicinttop() {
long top = stack.peek();
if (top > 0) {
return (int) (min + top);
} else {
return (int) min;
}
}
publicintgetMin() {
return (int) min;
}
The thought is to store the gap between the current value and min value, while the only problem is int is 4 bit so the Max gap = Integer.MAXVALUE - Integer.MINVALUE, and that value beyond int, so the author init the min value as long.
Another 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
publicclassMinStack{
static class Element{
finalint value;
finalint min;
Element(int value, int min){
this.value = value;
this.min = min;
}
}
Stack<Element>stack = new Stack<Element>();
publicvoidpush(int x) {
int min = (stack.isEmpty()) ? x : Math.min(x, stack.peek().min);
stack.push(new Element(x, min));
}
publicvoidpop() {
stack.pop();
}
publicinttop() {
return stack.peek().value;
}
publicintgetMin() {
return stack.peek().min;
}
}
Review Stack
Here’s the source code, compose by one Constructor and five Method