昨日一题 1670. 设计前中后队列(中等,列表)

昨日一题 1670. 设计前中后队列(中等,列表)_第1张图片

  1. 维护左右两个队列,控制左队列的长度比右队列长,且不超过1
  2. pushFront 往左队列的左边添加元素
  3. pushMiddle 往左队列的右边或者右队列的左边添加元素
  4. 其余同理,可以参照代码
class FrontMiddleBackQueue:

    def __init__(self):
        self.llist, self.rlist = [], []

    def pushFront(self, val: int) -> None:
        self.llist.insert(0, val)
        if len(self.llist) > len(self.rlist) + 1:
            self.rlist.insert(0, self.llist.pop())

    def pushMiddle(self, val: int) -> None:
        if len(self.llist) > len(self.rlist):
            self.rlist.insert(0, self.llist.pop())
        self.llist.append(val)

    def pushBack(self, val: int) -> None:
        self.rlist.append(val)
        if len(self.rlist) > len(self.llist):
            self.llist.append(self.rlist.pop(0))

    def popFront(self) -> int:
        if len(self.llist) == 0:
            return -1
        ans = self.llist.pop(0)
        if len(self.rlist) > len(self.llist):
            self.llist.append(self.rlist.pop(0))
        return ans

    def popMiddle(self) -> int:
        if len(self.llist) == 0:
            return -1
        ans = self.llist.pop()
        if len(self.rlist) > len(self.llist):
            self.llist.append(self.rlist.pop(0))
        return ans

    def popBack(self) -> int:
        if len(self.llist) == 0:
            return -1
        if len(self.rlist) == 0:
            return self.llist.pop()
        ans = self.rlist.pop()
        if len(self.llist) > len(self.rlist) + 1:
            self.rlist.insert(0, self.llist.pop())
        return ans

你可能感兴趣的:(用Python刷力扣,python,算法,leetcode)