Leetcode 155

HAHA 先自我吹嘘一波,之前博主写的博客<数据结构 -- 栈举例>正好完美匹配这道题目,一开始练手和学习都很适合.

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) -- 将元素 x 推入栈中。
  • pop() -- 删除栈顶的元素。
  • top() -- 获取栈顶元素。
  • getMin() -- 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

方法一:弱智方法,投机取巧

class MinStack(object):

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

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        

    def pop(self):
        """
        :rtype: void
        """
        self.stack.pop()

    def top(self):
        """
        :rtype: int
        """
        return self.stack[-1]

    def getMin(self):
        """
        :rtype: int
        """
        return min(self.stack)

方法二:要想效率高,主要优化的地方就是获取最小值那个方法,实际上这个函数本身没有优化的意义,关键是在类的其他方法添加一些,简化直接去最小值的时间复杂度,而不影响其他类方法的效率

class MinStack(object):

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

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        if self.min > x or self.min is None:
            self.min = x
        

    def pop(self):
        """
        :rtype: void
        """
        a = self.stack.pop()
        if len(self.stack) == 0:
            self.min = None
            return a
        elif a == self.min:
            self.min = self.stack[0]
            for item in self.stack:
                if item < self.min:
                    self.min = item

    def top(self):
        """
        :rtype: int
        """
        return self.stack[-1]

    def getMin(self):
        """
        :rtype: int
        """
        return self.min

猜你喜欢

转载自blog.csdn.net/jhlovetll/article/details/84028637