๊ฐ๋ฐ/๐ค ์๊ณ ๋ฆฌ์ฆ
[leetcode][Medium][Stack] 155. Min Stack ํ์ด, ํด์ค (python)
ttoance
2023. 11. 6. 23:21
https://leetcode.com/problems/min-stack/
1์ฐจ ํ์ด
๊ฐ๋ฒผ์ด ์คํ ๋ฌธ์ ์ผ๊ฑฐ๋ผ ์๊ฐํ๋๋ฐ, getMin ๋ถ๋ถ์์ ์ด๋ป๊ฒ O(1)์ ๋ง๋ค๊น ์ ๊น ๊ณ ๋ฏผํ๋ค.
๊ทธ๋ฌ๋ค๊ฐ ์ด์ฒํผ ์คํ์ด๋๊น ๊ทธ๋๋ง๋ค ์ต์๊ฐ์ ์ ์ฅํด๋๊ณ pop์ ๊ฐ์ด popํด์ฃผ๋ฉด ๋ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์ ์๋์ฒ๋ผ ๊ตฌํํ๋ค.
class MinStack(object):
def __init__(self):
self.minStack = [sys.maxsize]
self.stack = []
def push(self, val):
"""
:type val: int
:rtype: None
"""
if (self.minStack[-1] > val):
self.minStack.append(val)
else:
self.minStack.append(self.minStack[-1])
self.stack.append(val)
def pop(self):
"""
:rtype: None
"""
self.stack.pop()
self.minStack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minStack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
ํด์ค
https://www.youtube.com/watch?v=qkLl7nAwDPo
๋์ผํ๊ฒ minStack์ ๋ง๋ค์ด์ ์งํํ๋ค.
def __init__(self):
self.stack = []
self.minStack = []
def push(self, val):
"""
:type val: int
:rtype: None
"""
self.stack.append(val)
val = min(val, self.minStack[-1] if self.minStack else val) # minStack ๊ฐ์ด ์์๋๋ง
self.minStack.append(val)
def pop(self):
"""
:rtype: None
"""
self.stack.pop()
self.minStack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minStack[-1]
๋ฐ์ํ