-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
1172.java
53 lines (47 loc) · 1.48 KB
/
1172.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
__________________________________________________________________________________________________
class DinnerPlates {
int capacity;
List<Stack<Integer>> stacks;
TreeSet<Integer> pushable;
TreeSet<Integer> popable;
public DinnerPlates(int cap) {
capacity = cap;
stacks = new ArrayList<>();
pushable = new TreeSet<>();
popable = new TreeSet<>();
}
public void push(int val) {
if (pushable.isEmpty()) {
pushable.add(stacks.size());
stacks.add(new Stack<>());
}
int index = pushable.first();
Stack<Integer> stack = stacks.get(index);
stack.push(val);
popable.add(index);
if (stack.size() == capacity) {
pushable.remove(index);
}
}
public int pop() {
if (popable.size() == 0) {
return -1;
}
int index = popable.last();
return popAtStack(index);
}
public int popAtStack(int index) {
if (!popable.contains(index)) {
return -1;
}
Stack<Integer> stack = stacks.get(index);
int res = stack.pop();
pushable.add(index);
if (stack.size() == 0) {
popable.remove(index);
}
return res;
}
}
__________________________________________________________________________________________________
__________________________________________________________________________________________________