【LeetCode】155. Min Stack 最小栈 (Python&C++)
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/min-stack/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.
minStack.getMin(); --> Returns -2.
解题方法
栈同时保存当前值和最小值
题目要求在常数时间内获得栈中的最小值,因此不能在getMin()的时候再去计算最小值,最好应该在push或者pop的时候就已经计算好了当前栈中的最小值。
前排的众多题解中,基本都讲了「辅助栈」的概念,这是一种常见的思路,但是有没有更容易懂的方法呢?
可以用一个栈,这个栈同时保存的是每个数字进栈的时候的值与栈内最小值。即每次新元素 x 入栈的时候保存一个元组:(当前值 x,栈内最小值)。
这个元组是一个整体,同时进栈和出栈。即栈顶同时有值和栈内最小值,top()函数是获取栈顶的当前值,即栈顶元组的第一个值; getMin()函数是获取栈内最小值,即栈顶元组的第二个值;pop()函数时删除栈顶的元组。
每次新元素入栈时,要求新的栈内最小值:比较当前新插入元素 x 和 当前栈内最小值(即栈顶元组的第二个值)的大小。
- 新元素入栈:当栈为空,保存元组
(x, x);当栈不空,保存元组(x, min(此前栈内最小值, x))) - 出栈:删除栈顶的元组。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
if not self.stack:
self.stack.append((x, x))
else:
self.stack.append((x, min(x, self.stack[-1][1])))
def pop(self):
"""
:rtype: void
"""
self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1][0]
def getMin(self):
"""
:rtype: int
"""
return self.stack[-1][1]
# 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()
辅助栈
同步栈
也可以使用一个辅助栈,专门保存到目前为止的最小值。
所谓「同步栈」是指,辅助栈存储的最小值的push和pop完全与保存元素栈保持同步。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if not self.min:
self.min.append(x)
else:
self.min.append(min(self.min[-1], x))
def pop(self):
"""
:rtype: void
"""
self.stack.pop()
self.min.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min[-1]
# 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()
C++代码如下:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (!mins.empty() && x > mins.top()) {
mins.push(mins.top());
} else {
mins.push(x);
}
values.push(x);
}
void pop() {
values.pop();
mins.pop();
}
int top() {
return values.top();
}
int getMin() {
return mins.top();
}
private:
stack<int> values;
stack<int> mins;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
不同步栈
也使用一个辅助栈,但这个辅助栈与元素的插入不是同步的。
- 当插入元素 x 小于等于辅助栈的栈顶元素时,才把 x 插入到辅助栈的栈顶。
- 当弹出的元素 x 等于辅助栈的栈顶元素时,才把辅助栈的栈顶也弹出。
因此该辅助栈是一个单调递减栈。
C++ 代码如下:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
st.push(x);
if (min_values.size() == 0) {
min_values.push(x);
} else {
if (x <= min_values.top()) {
min_values.push(x);
}
}
}
void pop() {
int cur = st.top();
st.pop();
if (cur == min_values.top()) {
min_values.pop();
}
}
int top() {
return st.top();
}
int getMin() {
return min_values.top();
}
private:
stack<int> st;
stack<int> min_values;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
日期
2018 年 2 月 4 日
2018 年 11 月 24 日 —— 周六快乐
2019 年 9 月 18 日 —— 今日又是九一八
【LeetCode】155. Min Stack 最小栈 (Python&C++)的更多相关文章
- [LeetCode] 155. Min Stack 最小栈
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- [LeetCode] 0155. Min Stack 最小栈 & C++Runtime加速
题目 Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. ...
- 155 Min Stack 最小栈
设计一个支持 push,pop,top 操作,并能在常量时间内检索最小元素的栈. push(x) -- 将元素x推入栈中. pop() -- 删除栈顶的元素. top() -- 获取 ...
- [CareerCup] 3.2 Min Stack 最小栈
3.2 How would you design a stack which, in addition to push and pop, also has a function min which r ...
- leetcode 155. Min Stack 、232. Implement Queue using Stacks 、225. Implement Stack using Queues
155. Min Stack class MinStack { public: /** initialize your data structure here. */ MinStack() { } v ...
- LeetCode 155 Min Stack(最小栈)
翻译 设计支持push.pop.top和在常量时间内检索最小元素的栈. push(x) -- 推送元素X进栈 pop() -- 移除栈顶元素 top() -- 得到栈顶元素 getMin() -- 检 ...
- [LeetCode] Min Stack 最小栈
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- lintcode 中等题:Min stack 最小栈
题目 带最小值操作的栈 实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值. 你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成. 解题 可以定义 ...
- [LintCode] Min Stack 最小栈
Implement a stack with min() function, which will return the smallest number in the stack. It should ...
随机推荐
- 用python写的推箱子搜索程序
1 # -*- coding: gbk -*- 2 from functools import reduce 3 from copy import deepcopy 4 import re 5 def ...
- Celery进阶
Celery进阶 在你的应用中使用Celery 我们的项目 proj/__init__.py /celery.py /tasks.py 1 # celery.py 2 from celery ...
- git 的基本流程
有个本地文件 打开 新建一个 打开git $ git push origin master 这里是上传文件. (你每次上传的时候,都要先提交到本地的仓库...然后再上传) github上就有了 如何 ...
- [学习总结]3、Android---Scroller类(左右滑动效果常用的类)
参考资料:http://blog.csdn.net/vipzjyno1/article/details/24592591 非常感谢这个兄弟! 在android学习中,动作交互是软件中重要的一部分,其中 ...
- android转换透明度
比方说 70% 白色透明度. 就用255*0.7=185.5 在把185.5转换成16进制就是B2 你只需要写#B2FFFFFF 如果是黑色就换成6个0就可以了.前2位是控制透明度的.
- Windows 下 Node.js 开发环境搭建
1.利用CentOS Linux系统自带的yum命令安装.升级所需的程序库: sudo -s LANG=C yum -y install gcc gcc-c++ autoconf libjpeg li ...
- redis入门到精通系列(九):redis哨兵模式详解
(一)哨兵概述 前面我们讲了redis的主从复制,为了实现高可用,会选择一台服务器作为master,多台服务器作为slave.现在有这样一种情况,master宕机了,这时系统会选择一台slave作为m ...
- @RestController和@Controller的区别与作用
在springMvc中controller层类上的要使用@Controller来注明该类属于控制层,在controller层常返回的数据形式有以下几种: 页面:静态页面 ModelAndView:返回 ...
- Spring MVC与html页面的交互(以传递json数据为例)
一.导入相jar包 主要包括spring相关jar包和fastjson jar包,具体步骤略. 二.配置相关文件 1.配置web.xml文件 <?xml version="1.0&qu ...
- 一文详解 纹理采样与Mipmap纹理——构建山地渲染效果
在开发一些相对较大的场景时,例如:一片铺满相同草地纹理的丘陵地形,如果不采用一些技术手段,就会出现远处的丘陵较近处的丘陵相比更加的清晰的视觉效果,而这种效果与真实世界中近处的物体清晰远处物体模糊的效果 ...