Problem:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
Example 1:
-Summary-
Use tuple to save the minimum value and the current value of the stack.
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
if not self.stack:
self.stack.append((x,x))
else:
self.stack.append((x,min(x,self.stack[-1][1])))
def pop(self) -> None:
if self.stack:
self.stack.pop()
def top(self) -> int:
if self.stack:
return self.stack[-1][0]
else:
return None
def getMin(self) -> int:
if self.stack:
return self.stack[-1][1]
else:
return None
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]
'LeetCode > Top Interview Q. - Easy' 카테고리의 다른 글
LeetCode. Shuffle an Array (0) | 2020.06.24 |
---|---|
LeetCode. Reverse Bits (0) | 2020.06.22 |
LeetCode. Pascal's Triangle (0) | 2020.06.21 |
LeetCode. Missing Number [Bit] (0) | 2020.06.19 |
LeetCode.Hamming Distance [Bit] (0) | 2020.06.18 |
댓글