7/26/2020

[LeetCode] 155. Min Stack

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

Should save current minimum value in stack for O(1) time complexity.

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []

    def push(self, x: int) -> None:
        if len(self.stack) == 0:
            self.stack.append({'value': x, 'min': x})
        else:
            self.stack.append({'value': x, 'min': min(x, self.stack[-1]['min'])})
        
    def pop(self) -> None:
        del self.stack[-1]

    def top(self) -> int:
        return self.stack[-1]['value']
        

    def getMin(self) -> int:
        return self.stack[-1]['min']


# 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()

No comments:

Post a Comment