본문 바로가기
Python/PS in Python

LeetCode 155. Min Stack - Python

by Air’s Big Data 2020. 9. 9.

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]

 

(참고 사이트)

bhsbhs235.github.io/algorithm/2020/02/09/leetcode155.html

댓글