๊ฐœ๋ฐœ/๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

[leetcode][Medium][Stack] 155. Min Stack ํ’€์ด, ํ•ด์„ค (python)

ttoance 2023. 11. 6. 23:21

https://leetcode.com/problems/min-stack/

 

Min Stack - LeetCode

Can you solve this real interview question? Min Stack - Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: * MinStack() initializes the stack object. * void push(int val) pushes t

leetcode.com

 

 

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]
๋ฐ˜์‘ํ˜•