包含min函数的栈(important)

题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

解题思路:
使用一个辅助栈,当当前数字比辅助栈顶元素小的时候,当前元素进栈;否则将辅助栈的栈顶元素进栈。
也就是说,对于栈里边的每个元素,都在辅助栈的对应位置放上它这里时候的最小元素。

python solution:

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack = []
        self.support = []
        
    def push(self, node):
        if len(self.stack)==0:
            self.stack.append(node)
            self.support.append(node)
        else:
            self.stack.append(node)
            if node<self.support[-1]:
                self.support.append(node)
            else:
                self.support.append(self.support[-1])
            
    def pop(self):
        self.support.pop(-1)
        return self.stack.pop(-1)
        
    def top(self):
        return self.stack[-1]
    
    def min(self):
        return self.support[-1]
posted @ 2019-03-02 17:53  bernieloveslife  阅读(132)  评论(0编辑  收藏  举报