《剑指offer》面试题8:包含min函数的栈

题目描述

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

解题思路:

这个题目我们首先拿到的代码如下:

# -*- coding:utf-8 -*-
class Solution:
    def push(self, node):
        #入栈
    def pop(self):
        # 出栈
    def top(self):
        # 显示出最top的元素是什么,并不弹出
    def min(self):
        # write code here

一共有三个函数,分别是push,pop,top,min,push代表入栈,pop代表出栈,top代表栈顶的元素是哪一个并打印出来,min代表当前栈中最小的元素是哪一个。我们首先完成最基础的一个栈的结构:

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack=[]
    def push(self, node):
        #入栈
        self.stack.append(node)
    def pop(self):
        # 出栈
        if self.stack==[]:
            return None
        self.minValue.pop()#和stack一起pop
        return self.stack.pop()
    def top(self):
        # 显示出最top的元素是什么,并不弹出
        if self.stack==[]:
            return None
        return self.stack.stack[-1]
    def min(self):

        # write code here

我们在函数的自定义层定义了一个stack栈的结构,这样一个最基础的stack就拥有了所有的属性,包括压栈,出栈等。不过我们怎样找出一个栈当中最小的元素呢?

方法:

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack=[]
        self.minValue=[]
    def push(self, node):
        #入栈
        self.stack.append(node)
        if self.minValue:
            #[3,2] node:1
            #[3,2,1]
            #[3,2],node:4
            #[3,2,2]
            #这样就做到了保持Minvalue的元素个数和stack保持一致,同时增加的都是越来越小的数
            if self.minValue[-1]>node:
                self.minValue.append(node)
            else:
                self.minValue.append(self.minValue[-1])
        else:
            self.minValue.append(node)
    def pop(self):
        # 出栈
        if self.stack==[]:
            return None
        self.minValue.pop()#和stack一起pop
        return self.stack.pop()
    def top(self):
        # 显示出最top的元素是什么,并不弹出
        if self.stack==[]:
            return None
        return self.stack.stack[-1]
    def min(self):
        if self.minValue==[]:
            return None
        else:
            return self.minValue[-1]
        # write code here
原文地址:https://www.cnblogs.com/geeksongs/p/13491569.html