-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathDinner Plate Stacks.py
56 lines (50 loc) · 1.59 KB
/
Dinner Plate Stacks.py
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
class DinnerPlates:
def __init__(self, capacity: int):
self.heap = []
self.stacks = []
self.capacity = capacity
def push(self, val: int) -> None:
if self.heap:
index = heapq.heappop(self.heap)
if index < len(self.stacks):
self.stacks[index].append(val)
else:
self.push(val)
elif self.stacks:
lastStack = self.stacks[-1]
if len(lastStack) != self.capacity:
lastStack.append(val)
else:
stack = deque()
stack.append(val)
self.stacks.append(stack)
else:
stack = deque()
stack.append(val)
self.stacks.append(stack)
def pop(self) -> int:
while self.stacks:
lastStack = self.stacks[-1]
if lastStack:
val = lastStack.pop()
if not lastStack:
self.stacks.pop()
return val
else:
self.stacks.pop()
return -1
def popAtStack(self, index: int) -> int:
if index == len(self.stacks) - 1:
return self.pop()
if index < len(self.stacks):
stack = self.stacks[index]
if stack:
val = stack.pop()
heapq.heappush(self.heap, index)
return val
return -1
# Your DinnerPlates object will be instantiated and called as such:
# obj = DinnerPlates(capacity)
# obj.push(val)
# param_2 = obj.pop()
# param_3 = obj.popAtStack(index)