[LeetCode][Python3] 155. Min Stack
2018. 9. 28. 01:02 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/min-stack/description/
My Solution :
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
if self.stack:
self.stack.append((x, min(x, self.stack[-1][1])))
else:
self.stack.append((x, x))
def pop(self):
"""
:rtype: void
"""
self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1][0]
def getMin(self):
"""
:rtype: int
"""
return self.stack[-1][1]
# 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()
Comment :
stack 자료구조이기 때문에 "현재까지의 최소값" 을 pair로 기록해두는 전략이다. 나중에 더 최소값이 입력되더라도 상관이 없다. stack 자료구조이기 때문에 후입선출이라 아래쪽 최소값에는 영향을 주지 않는다.
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 206. Reverse Linked List (0) | 2018.10.01 |
---|---|
[LeetCode][Python3] 198. House Robber (0) | 2018.10.01 |
[LeetCode][Python3] 169. Majority Element (0) | 2018.10.01 |
[LeetCode][Python3] 160. Intersection of Two Linked Lists (0) | 2018.09.28 |
[LeetCode][Python3] 141. Linked List Cycle (0) | 2018.09.28 |
[LeetCode][Python3] 136. Single Number (0) | 2018.09.27 |
[LeetCode][Python3] 121. Best Time to Buy and Sell Stock (0) | 2018.09.27 |
[LeetCode][Python3] 104. Maximum Depth of Binary Tree (0) | 2018.09.27 |
최근에 달린 댓글 최근에 달린 댓글