题目地址: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 和 当前栈内最小值(即栈顶元组的第二个值)的大小。

  1. 新元素入栈:当栈为空,保存元组 (x, x);当栈不空,保存元组 (x, min(此前栈内最小值, x)))
  2. 出栈:删除栈顶的元组。
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()

辅助栈

同步栈

也可以使用一个辅助栈,专门保存到目前为止的最小值。

所谓「同步栈」是指,辅助栈存储的最小值的pushpop完全与保存元素栈保持同步。

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();
*/

不同步栈

也使用一个辅助栈,但这个辅助栈与元素的插入不是同步的。

  1. 当插入元素 x 小于等于辅助栈的栈顶元素时,才把 x 插入到辅助栈的栈顶。
  2. 当弹出的元素 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++)的更多相关文章

  1. [LeetCode] 155. Min Stack 最小栈

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  2. [LeetCode] 0155. Min Stack 最小栈 & C++Runtime加速

    题目 Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. ...

  3. 155 Min Stack 最小栈

    设计一个支持 push,pop,top 操作,并能在常量时间内检索最小元素的栈.    push(x) -- 将元素x推入栈中.    pop() -- 删除栈顶的元素.    top() -- 获取 ...

  4. [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 ...

  5. 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 ...

  6. LeetCode 155 Min Stack(最小栈)

    翻译 设计支持push.pop.top和在常量时间内检索最小元素的栈. push(x) -- 推送元素X进栈 pop() -- 移除栈顶元素 top() -- 得到栈顶元素 getMin() -- 检 ...

  7. [LeetCode] Min Stack 最小栈

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  8. lintcode 中等题:Min stack 最小栈

    题目 带最小值操作的栈 实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值. 你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成. 解题 可以定义 ...

  9. [LintCode] Min Stack 最小栈

    Implement a stack with min() function, which will return the smallest number in the stack. It should ...

随机推荐

  1. NFS FTP SAMBA的区别

    Samba服务 samba是一个网络服务器,用于Linux和Windows之间共享文件. samba端口号 samba (启动时会预设多个端口) 数据传输的TCP端口 139.445 进行NetBIO ...

  2. chown & chmod用法

    chown & chmod 1. chown更改文件的属主&属组 NAME chown - 改变文件的属主和属组(change file owner and group) 用法 cho ...

  3. Webpack 打包 Javascript 详细介绍

    本篇我们主要介绍Webpack打包 Javascript.当然,除了可以打包Javascript之外,webpack还可以打包html.但是这不是我们本篇的重点.我们可以参考 Webpack HTML ...

  4. java四则运算规则

    java四则运算规则 1.基本规则 运算符:进行特定操作的符号.例如:+ 表达式:用运算符连起来的式子叫做表达式.例如:20 + 5.又例如:a + b 四则运算: 加:+ 减:- 乘:* 除:/ 取 ...

  5. MySQL索引背后的数据结构及算法原理 【转】

    摘要 本文以MySQL数据库为研究对象,讨论与数据库索引相关的一些话题.特别需要说明的是,MySQL支持诸多存储引擎,而各种存储引擎对索引的支持也各不相同,因此MySQL数据库支持多种索引类型,如BT ...

  6. 【leetcode】208. Implement Trie (Prefix Tree 字典树)

    A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...

  7. node环境变量配置

    1.Node.js 官方网站下载:https://nodejs.org/en/ 2.打开安装,傻瓜式下一步即可,然后配置环境变量 3.因为在执行例如npm install webpack -g等命令全 ...

  8. android 防止R被混淆,R类反射混淆,找不到资源ID

    在Proguard.cfg中添加 -keep class **.R$* { *;   }

  9. 将图片打印到word中

    1.生成模板文件 工具类: package com.sfec.snmgr.track.utils;import com.alibam.core.wechat.util.QRCodeUtil;impor ...

  10. Quartz使用AutoFac依赖注入问题小结

    theme: channing-cyan highlight: a11y-dark 背景 最近在做一个需求,就是在Job中捕捉异常,然后通过邮件或者消息的方式推送给指定人员,在需求实现的过程中遇到的一 ...