forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
design-front-middle-back-queue.py
65 lines (54 loc) · 1.46 KB
/
design-front-middle-back-queue.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
57
58
59
60
61
62
63
64
65
# Time: O(1)
# Space: O(n)
import collections
class FrontMiddleBackQueue(object):
def __init__(self):
self.__left, self.__right = collections.deque(), collections.deque()
def pushFront(self, val):
"""
:type val: int
:rtype: None
"""
self.__left.appendleft(val)
self.__balance()
def pushMiddle(self, val):
"""
:type val: int
:rtype: None
"""
if len(self.__left) > len(self.__right):
self.__right.appendleft(self.__left.pop())
self.__left.append(val)
def pushBack(self, val):
"""
:type val: int
:rtype: None
"""
self.__right.append(val)
self.__balance()
def popFront(self):
"""
:rtype: int
"""
val = (self.__left or collections.deque([-1])).popleft()
self.__balance()
return val
def popMiddle(self):
"""
:rtype: int
"""
val = (self.__left or [-1]).pop()
self.__balance()
return val
def popBack(self):
"""
:rtype: int
"""
val = (self.__right or self.__left or [-1]).pop()
self.__balance()
return val
def __balance(self):
if len(self.__left) > len(self.__right)+1:
self.__right.appendleft(self.__left.pop())
elif len(self.__left) < len(self.__right):
self.__left.append(self.__right.popleft())