LeetCode初级算法-设计问题02:最小栈

leetcode初级算法--设计问题02:最小栈 一、引子 这是由leetcode官方推出的的经典面试题目清单~
这个模块对应的是探索的初级算法~旨在帮助入门算法。我们第一遍刷的是leetcode推荐的题目。
二、题目 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。 pop() -- 删除栈顶的元素。 top() -- 获取栈顶元素。 getmin() -- 检索栈中的最小元素。 示例:
minstack minstack = new minstack();minstack.push(-2);minstack.push(0);minstack.push(-3);minstack.getmin(); --> 返回 -3.minstack.pop();minstack.top(); --> 返回 0.minstack.getmin(); --> 返回 -2. 1、思路 第一种方法:
用列表模拟栈,push、pop、top和getmin分别对应list.append()、list.pop()、list[-1]和min()操作
第二种方法:
引入minstack列表存放最小值
2、编程实现 第一种方法:
python
class minstack(object): def __init__(self): initialize your data structure here. self.l = [] def push(self, x): :type x: int :rtype: none if x is none: pass else: self.l.append(x) def pop(self): :rtype: none if self.l is none: return 'error' else: self.l.pop(-1) def top(self): :rtype: int if self.l is none: return 'error' else: return self.l[-1] def getmin(self): :rtype: int if self.l is none: return 'error' else: return min(self.l)# your minstack object will be instantiated and called as such:# obj = minstack()# obj.push(x)# obj.pop()# param_3 = obj.top()# param_4 = obj.getmin() 第二种方法:
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 not self.minstack or self.minstack[-1]>=x: self.minstack.append(x) def pop(self): #移除栈顶元素时,判断是否移除栈中最小值 :rtype: void if self.minstack[-1]==self.stack[-1]: del self.minstack[-1] self.stack.pop() def top(self): :rtype: int return self.stack[-1] def getmin(self): :rtype: int return self.minstack[-1]  
本文由博客一文多发平台 openwrite 发布!

务实推进TD-SCDMA产业健康发展
吉方嵌入式工控机让工业检测更精准、更灵活!
9月三日连发三部全面屏手机,小米mix2、iphone8、三星note8国行版要搞大事情!
由三星提供!iPhone 8鲸吞一亿块OLED显示屏
矽力杰车规级音频功放
LeetCode初级算法-设计问题02:最小栈
福特豪掷10亿美金收购AI初创Argo 解决自动驾驶软件问题
青海电网资源优化配置能力和安全稳定运行水平
基于GSM短信模块的定位跟踪系统设计方案
陕西省电线电缆抽查4批次不合格 涉及万谛电缆等企业
晶体管技术来降低功耗的一些方案与分析
第一性原理软件携手曙光智算共同助推材料创新
思睿达CR6889B方案能否替换XX11?测试数据分析
蓝牙5.0正式启用 竟然多了这么厉害的功能?
盈趣科技荣获2019年度金牛“最具投资价值奖”
2025年全球5G连接数量将达到14亿
移动电源爆炸频频,将如何选择?
什么是根系分析仪,它可以分析作物的哪些方面
基于单片机的数控恒流源电路的设计
英特尔即将推出Tiger Lake 系统芯片(SoC)架构