File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: push: O(logn)
2
+ # pop: O(1), amortized
3
+ # popAtStack: O(logn)
4
+ # Space: O(n * c)
5
+
6
+ import heapq
7
+
8
+
9
+ class DinnerPlates (object ):
10
+
11
+ def __init__ (self , capacity ):
12
+ """
13
+ :type capacity: int
14
+ """
15
+ self .__stks = []
16
+ self .__c = capacity
17
+ self .__min_heap = []
18
+
19
+ def push (self , val ):
20
+ """
21
+ :type val: int
22
+ :rtype: None
23
+ """
24
+ if self .__min_heap :
25
+ l = heapq .heappop (self .__min_heap )
26
+ if l < len (self .__stks ):
27
+ self .__stks [l ].append (val )
28
+ return
29
+ self .__min_heap = [] # nothing is valid in min heap
30
+ if not self .__stks or len (self .__stks [- 1 ]) == self .__c :
31
+ self .__stks .append ([])
32
+ self .__stks [- 1 ].append (val )
33
+
34
+ def pop (self ):
35
+ """
36
+ :rtype: int
37
+ """
38
+ while self .__stks and not self .__stks [- 1 ]:
39
+ self .__stks .pop ()
40
+ if not self .__stks :
41
+ return - 1
42
+ return self .__stks [- 1 ].pop ()
43
+
44
+ def popAtStack (self , index ):
45
+ """
46
+ :type index: int
47
+ :rtype: int
48
+ """
49
+ if index >= len (self .__stks ) or not self .__stks [index ]:
50
+ return - 1
51
+ heapq .heappush (self .__min_heap , index )
52
+ return self .__stks [index ].pop ()
You can’t perform that action at this time.
0 commit comments