155. Min Stack
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.
Constraints:
- Methods pop, top and getMin operations will always be called on non-empty stacks.
Example:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Solution:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minStack = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.stack.append(x)
if not self.minStack or self.minStack[-1] >= x:
self.minStack.append(x)
def pop(self):
"""
:rtype: nothing
"""
tmp = self.stack.pop()
if tmp == self.minStack[-1]:
self.minStack.pop()
def top(self):
"""
:type x: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minStack[-1]
(참고 사이트)
'Python > PS in Python' 카테고리의 다른 글
[LeetCode] Easy 문제 풀이 모음 - Python (0) | 2020.09.12 |
---|---|
LeetCode 198. House Robber - Python (0) | 2020.09.11 |
LeetCode 53. Maximum Subarray - Python (0) | 2020.09.07 |
LeetCode 101. Symmetric Tree - Python (0) | 2020.09.04 |
LeetCode 1. Two Sum - Python (0) | 2020.08.31 |
댓글