[LeetCode] 155. Min Stack_Easy tag: 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.

Example:

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

这个题目可以就用stack/array来实现,只不过我们不再仅仅只是append进入val,also 当前stack的最小值,然后两个作为一个tuple来进入到stack/array里面。

Note: 这里可以问面试官,如果stack为空,那么stack.pop() 与stack.top()要返回什么。这里我假设他们都返回 -1

Code

class MinStack:
    def __init__(self):
        self.stack = []
    def push(self, x: int) -> None:
        self.stack.append((x, x if not self.stack else min(x, self.stack[-1][1])))    # 若是只有一个if 和else,python可以用一行来代替
    def pop(self) -> None:
        if self.stack:
            self.stack.pop()
    def getMin(self) -> int:
        return self.stack[-1][1] if self.stack else -1    # 返回什么问面试官
    def top(self) -> int:
        return self.stack[-1][0] if self.stack else -1    # 返回什么问面试官

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/10854578.html