-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStackMin.java
54 lines (43 loc) · 866 Bytes
/
StackMin.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
/*
Stack Min: How would you design a stack which, in addition to push and pop, has a function min
which returns the minimum element? Push, pop and min should all operate in 0(1) time.
*/
class Stack{
List<Integer> list;
int top;
Map<Integer,Integer> map;
Stack(){
list = new ArrayList<>();
map = new HashMap<>();
top = -1;
}
boolean isEmpty(){
return list.isEmpty();
}
void push(int x){
int min = calculateMin(x);
list.add(++top,x);
map.put(top,min);
}
boolean pop(){
if(top == -1){
return false;
}
list.remove(top);
map.remove(top);
top--;
return true;
}
int min(){
if(top == -1) {
throw new EmptyStackException();
}
return map.get(top);
}
private int calculateMin(int x){
if(top == -1){
return x;
}
return Math.min(map.get(top),x);
}
}