forked from lgaBug/algorithm014-algorithm014
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMinStack155.java
More file actions
95 lines (84 loc) · 2.27 KB
/
MinStack155.java
File metadata and controls
95 lines (84 loc) · 2.27 KB
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
package Week_01;
import java.lang.reflect.Method;
public class MinStack155 {
public static void main(String[] args) {
MinStack s = new MinStack();
s.push(3);
System.out.println(s.top() + " " + s.getMin());
s.push(2);
System.out.println(s.top() + " " + s.getMin());
s.push(4);
System.out.println(s.top() + " " + s.getMin());
s.push(1);
System.out.println(s.top() + " " + s.getMin());
s.pop();
}
}
class MinStack {
int[] stack;
int[] minStack;
int size;
int length;
/** initialize your data structure here. */
public MinStack() {
int initLength = 10;
this.size = 0;
this.length = initLength;
this.stack = new int[initLength];
this.minStack = new int[initLength];
}
public void isFull() {
if (this.length > this.size) {
return;
}
int incr = 5;
int[] newStack = new int[this.length + incr];
int[] newMinStack = new int[this.length + incr];
System.arraycopy(this.stack, 0, newStack, 0, this.length);
System.arraycopy(this.minStack, 0, newMinStack, 0, this.length);
this.stack = newStack;
this.minStack = newMinStack;
this.length += incr;
}
public boolean isEmpty() {
return this.size == 0;
}
public void push(int val) {
this.isFull();
this.stack[this.size] = val;
if (this.isEmpty()) {
this.minStack[this.size] = val;
} else {
this.minStack[this.size] = Math.min(this.minStack[this.size - 1], val);
}
this.size++;
}
public void pop() {
if (this.isEmpty()) {
return;
}
this.stack[this.size-1] = 0;
this.minStack[this.size-1] = 0;
this.size--;
}
public int top() {
if (this.isEmpty()) {
return 0;
}
return this.stack[this.size-1];
}
public int getMin() {
if (this.isEmpty()) {
return 0;
}
return this.minStack[this.size-1];
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/