Leetcode 1172. 餐盤棧 - python 解法

題目連接: leetocde 1172python

解題思路

這個題目用 python 作很簡單
python 中使用 list 實現棧
咱們定義幾個類的屬性:app

  1. self.s = [[]] ,一個list 的 list ,這裏面是咱們要操做的全部的棧
  2. self.cur_id = 0 表明下一個 push 操做對應的棧的 id
  3. self.capacity 就是每一個棧的容量

操做:code

  1. push:須要先判斷 cur_id 指向的棧還有沒有空間,若是沒有,看看右邊還有沒有棧,有就 cur_id 加一,不然添加新棧
  2. pop:判斷最右邊的棧是否有元素,沒有就銷燬棧並左移
  3. popAtStack:判斷指定棧是否存在和有元素

代碼

class DinnerPlates:

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.s = [[]]
        self.cur_id = 0


    def push(self, val: int) -> None:
        while True:
            if len(self.s[self.cur_id]) < self.capacity: break
            self.cur_id += 1
            if len(self.s) == self.cur_id:
                self.s.append([])
        self.s[self.cur_id].append(val)


    def pop(self) -> int:
        i = len(self.s)-1
        while not self.s[i]:
            if i == 0: return -1
            self.s.pop()
            i -= 1
        self.cur_id = min(self.cur_id, i)
        return self.s[i].pop()


    def popAtStack(self, index: int) -> int:
        if index < len(self.s) and self.s[index]:
            self.cur_id = min(self.cur_id, index)
            return self.s[index].pop()
        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)
相關文章
相關標籤/搜索