[leetcode] 716。最大スタック@python



716 Max Stack Python



元の質問

push、pop、top、peekMax、popMaxをサポートする最大スタックを設計します。

push(x)–要素xをスタックにプッシュします。
pop()–スタックの一番上の要素を削除して返します。
top()–上部の要素を取得します。
peekMax()–スタック内の最大要素を取得します。
popMax()–スタック内の最大要素を取得し、それを削除します。最大要素が複数ある場合は、一番上の要素のみを削除してください。
例1:
MaxStackスタック=新しいMaxStack()
stack.push(5)
stack.push(1)
stack.push(5)
stack.top()-> 5
stack.popMax()-> 5
stack.top()-> 1
stack.peekMax()-> 5
stack.pop()-> 1
stack.top()-> 5
注意:
-1e7<= x <= 1e7
操作の数は10000を超えません。
スタックが空の場合、最後の4つの操作は呼び出されません。



解決

リストを使用して、押すたびにリストの左側に要素を追加します。

コード

class MaxStack(object): def __init__(self): ''' initialize your data structure here. ''' self.data = [] def push(self, x): ''' :type x: int :rtype: None ''' self.data.insert(0, x) def pop(self): ''' :rtype: int ''' return self.data.pop(0) def top(self): ''' :rtype: int ''' return self.data[0] def peekMax(self): ''' :rtype: int ''' return max(self.data) def popMax(self): ''' :rtype: int ''' ans = max(self.data) self.data.remove(ans) return ans # Your MaxStack object will be instantiated and called as such: # obj = MaxStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.peekMax() # param_5 = obj.popMax()