-
Notifications
You must be signed in to change notification settings - Fork 0
/
155. Min Stack
70 lines (56 loc) · 1.78 KB
/
155. Min Stack
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
/*
https://leetcode.com/problems/min-stack/description/
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.
*/
class MinStack {
static class StackElement {
private int value;
private int minBelow;
public StackElement() {
}
public StackElement(int value, int minBelow) {
this.value = value;
this.minBelow = minBelow;
}
public int getValue() {
return value;
}
public int getMinBelow() {
return minBelow;
}
}
private StackElement[] stack;
private int topIdx;
private int minimum = 999;
private static final int initialLength = 10000;
/**
* initialize your data structure here.
*/
public MinStack() {
this.stack = new StackElement[initialLength];
this.topIdx = -1;
}
public void push(int x) {
if (topIdx == -1) {
minimum = x;
}
stack[++topIdx] = new StackElement(x, x < minimum ? x : minimum);
minimum = minimum < x ? minimum : x;
}
public void pop() {
topIdx--;
if (topIdx > -1) {
minimum = stack[topIdx].getMinBelow();
}
}
public int top() {
return stack[topIdx].getValue();
}
public int getMin() {
return minimum;
}
}