-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathStackWithMin.java
executable file
·56 lines (53 loc) · 1.3 KB
/
StackWithMin.java
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
package ca.mcmaster.offer;
public class StackWithMin {
private int writeIndex = 0;
private Integer capacity;
private Object[] arr;
private Integer min = Integer.MAX_VALUE;
public StackWithMin(Integer capacity){
this.capacity = capacity;
arr = new Object[capacity];
}
class Item{
Integer value;
Integer minVal;
public Item(Integer value, Integer min){
this.value = value;
this.minVal = min;
}
}
public void push(int v){
this.min = Math.min(this.min, v);
if(writeIndex >= capacity)
throw new ArrayIndexOutOfBoundsException();
arr[writeIndex] = (Object)new Item(v, this.min);
writeIndex++;
}
public Integer pop(){
int readIndex = writeIndex - 1;
if(readIndex < 0)
throw new ArrayIndexOutOfBoundsException();
Item result = (Item)arr[readIndex];
writeIndex--;
return result.value;
}
public Integer min(){
int readIndex = writeIndex - 1;
if(readIndex < 0) throw new ArrayIndexOutOfBoundsException();
Item result = (Item)arr[readIndex];
return result.minVal;
}
public static void main(String[] args) {
StackWithMin stack = new StackWithMin(20);
for(int i = 5; i < 10; i++){
stack.push(i);
}
for(int i = 0; i < 5; i++){
stack.push(i);
}
for(int i = 0; i < 10; i++){
System.out.println(stack.min());
System.out.println(stack.pop());
}
}
}