1172. Dinner Plate Stacks
from sortedcontainers import SortedSet
class DinnerPlates (object ):
def __init__ (self , capacity ):
"""
:type capacity: int
"""
self .capacity = capacity
self .stacks = []
self .not_full = SortedSet ()
def push (self , val ):
"""
:type val: int
:rtype: None
"""
if not self .not_full :
self .stacks .append ([val ])
if self .capacity > 1 :
self .not_full .add (len (self .stacks ) - 1 )
else :
index = self .not_full [0 ]
self .stacks [index ].append (val )
if len (self .stacks [index ]) == self .capacity :
self .not_full .discard (index )
def pop (self ):
"""
:rtype: int
"""
return self .popAtStack (len (self .stacks ) - 1 )
def popAtStack (self , index ):
"""
:type index: int
:rtype: int
"""
if index < 0 or index >= len (self .stacks ) or not self .stacks [index ]:
return - 1
val = self .stacks [index ].pop ()
if index == len (self .stacks ) - 1 and not self .stacks [- 1 ]:
while self .stacks and not self .stacks [- 1 ]:
self .not_full .discard (len (self .stacks ) - 1 )
self .stacks .pop ()
else :
self .not_full .add (index )
return val
# 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)