
[Easy] 155. Min Stack
发布日期:2021-05-07 18:21:25
浏览次数:22
分类:精选文章
本文共 1399 字,大约阅读时间需要 4 分钟。
155. Min Stack
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 1:
Input["MinStack","push","push","push","getMin","pop","top","getMin"][[],[-2],[0],[-3],[],[],[],[]]Output[null,null,null,null,-3,null,0,-2]ExplanationMinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin(); // return -3minStack.pop();minStack.top(); // return 0minStack.getMin(); // return -2
Constraints: Methods pop, top and getMin operations will always be called on non-empty stacks.
Solution
Runtime: 48 ms, faster than 23.55% of C++ online submissions for Min Stack. Memory Usage: 16.1 MB, less than 100.00% of C++ online submissions for Min Stack.
class MinStack { private: stack s1, s2;public: /** initialize your data structure here. */ MinStack() { } void push(int x) { if(s2.empty() || x <= getMin()) s2.push(x); s1.push(x); } void pop() { if(s1.top()==getMin()) s2.pop(); s1.pop(); } int top() { return s1.top(); } int getMin() { return s2.top(); }};
使用双栈,一个存放当前最小元素,另一个存放所有元素。
入栈时,需要考虑是否是当前最小,出栈时,需要考虑两个栈是否都需出栈。发表评论
最新留言
感谢大佬
[***.8.128.20]2025年03月28日 00时08分19秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Python实现理解树,树的遍历,二分查找
2021-05-08
Python3.6爬虫记录
2021-05-08
搞清楚Spring Cloud架构原理的这4个点,轻松应对面试
2021-05-08
1月份2月份GitHub上最热门的23个Java开源项目
2021-05-08
maven安装
2021-05-08
2020第十五届全国大学生智能汽车竞赛——4X4矩阵键盘+Flash调参系统
2021-05-08
合并两个有序数组
2021-05-08
Ubuntu 环境下使用中文输入法
2021-05-08
小白学习Vue(?)--model选项的使用(自定义组件文本框双向绑定)
2021-05-08
聊聊我的五一小假期
2021-05-08
面向对象之异常处理:多路捕获
2021-05-08
Python简易五子棋
2021-05-08
MySQL8.0.19 JDBC下载与使用
2021-05-08
Windows安装MongoDB 4.2.8
2021-05-08
Vue新建项目——页面初始化
2021-05-08
Cent OS 7.6 服务器软件安装(这篇博客主要是为了方便我配置云主机的)
2021-05-08
MySQL使用系列文章
2021-05-08
Node.js包使用系列(一)——修改NPM全局下载和缓存路径
2021-05-08
TDengine使用(一)——TDengine下载与安装
2021-05-08
Node.js包使用系列(三)——常用npm包列表
2021-05-08