How to get the smaller one in two numbers


  • 0
    M

    I used one stack to solve the problem. The Python code is

    class MinStack:
    
    def __init__(self):
        self._stack = []
        self._min = None
    
    # @param x, an integer
    # @return an integer
    def push(self, x):
        if self._min is None:
            self._min = x
        self._stack.append(x - self._min)
        # self._min = min(self._min, x)
        if x < self._min:
             self._min = x
        return x
    
    # @return nothing
    def pop(self):
        if self._stack:
            temp = self._stack.pop()
            if not self._stack:
                self._min = None
            elif temp < 0:
                self._min -= temp
    
    # @return an integer
    def top(self):
        temp = self._stack[-1]
        if temp > 0:
            return temp + self._min
        else:
            return self._min
    
    # @return an integer
    def getMin(self):
        return self._min
    

    I found a very strange issue. In the push function, I use if statement, to ensure self._min always store the minimum number, and the program is accepted.

    However, if I choose min() function to do the same thing which was commented above the if statement, I always get a MLE error.
    What is the difference between min() and if?


  • 0
    M

    if your pop function returns nothing, how does this line makes sense?

    temp = self._stack.pop()


  • 0
    M

    self._stack.pop() is not self.pop(). self._stack is a list, of course it has a pop() function that return a value.
    My program is accepted. So the statement you mentioned above has no problem. It is the commented statement in push function make OJ give me MLE error.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.