站长网 资讯 教你快速找到及时序列的最小值

教你快速找到及时序列的最小值

推入元素到 mainstack,只有当当前元素小于tmpstack栈顶(实际存储为mainstack中元素索引)元素时,才入栈到tmpstack,入栈的是索引。 假设mainstack当前有n个元素,则tmpstack内元素至多有n个。等于n时,表明原入栈序列为单调递减序列。 出栈分析: 元素从m

推入元素到 mainstack,只有当当前元素小于tmpstack栈顶(实际存储为mainstack中元素索引)元素时,才入栈到tmpstack,入栈的是索引。

假设mainstack当前有n个元素,则tmpstack内元素至多有n个。等于n时,表明原入栈序列为单调递减序列。

出栈分析:

元素从mainstack出栈,但要注意出栈元素索引是否等于tmpstack栈顶,若是需要将tmpstack栈顶元素出栈。可以预知,栈顶索引一定小于等于出栈元素(在mainstack栈内)的索引。

这道题需要注意两点:

临时栈里推送的是主栈的元素索引

push时若临时栈为空,需要先推入此元素在主栈索引

代码

class MinStack(object): 

    def __init__(self): 

 

        """ 

        initialize your data structure here. 

        """ 

        self.mainstack= [] 

        self.tmpstack = [] 

推入元素:

def push(self, val): 

 

    """ 

    :type val: int 

    :rtype: None 

    """ 

 

    self.mainstack.append(val) 

 

    if not self.tmpstack: 

 

        self.tmpstack.append(len(self.mainstack)-1) 

 

    # smaller than top of tmpstack 

    if self.mainstack[self.tmpstack[-1]] > val: 

 

        self.tmpstack.append(len(self.mainstack)-1)  

出栈元素:

def pop(self): 

    """ 

    :rtype: None 

    """ 

 

    # min val of tmp stack equals top of mainstack 

    if self.tmpstack and self.tmpstack[-1] == len(self.mainstack)-1: 

        self.tmpstack.pop() 

 

    return self.mainstack.pop() 

def top(self): 

    """ 

    :rtype: int 

    """ 

 

    if self.mainstack: 

        return self.mainstack[-1] 

使用tmpstack辅助栈,换来了O(1)的查询最小复杂度

def getMin(self): 

    """ 

    :rtype: int 

    """ 

 

    if self.tmpstack: 

        return self.mainstack[self.tmpstack[-1]] 

本文来自网络,不代表站长网立场,转载请注明出处:https://www.zwzz.com.cn/html/biancheng/zx/2021/0527/6924.html

作者: dawei

【声明】:站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。
联系我们

联系我们

0577-28828765

在线咨询: QQ交谈

邮箱: xwei067@foxmail.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部