[勇者闯LeetCode] 155. Min Stack

来源:互联网 发布:vs2015 知乎 编辑:程序博客网 时间:2024/05/16 23:01

[勇者闯LeetCode] 155. Min Stacke

Description

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.

Information

  • Tags: Stack | Design
  • Difficulty: Easy

Solution

使用两个stack实现, 一个stack正常存储数值,另一个stack存储每次的最小值(保存最小值的变化序列)

Python Code

class MinStack(object):    def __init__(self):        """        initialize your data structure here.        """        self.stack = []        self.minstack = []    def push(self, x):        """        :type x: int        :rtype: void        """        self.stack.append(x)        if len(self.minstack) == 0 or self.minstack[-1] > x:            self.minstack.append(x)        else:            self.minstack.append(self.minstack[-1])    def pop(self):        """        :rtype: void        """        self.minstack.pop()        return self.stack.pop()    def top(self):        """        :rtype: int        """        return self.stack[-1]    def getMin(self):        """        :rtype: int        """        return self.minstack[-1]
原创粉丝点击