题目

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.

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) -- 将元素 x 推入栈中。
  • pop() -- 删除栈顶的元素。
  • top() -- 获取栈顶元素。
  • getMin() -- 检索栈中的最小元素。

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.

解法一

用两个栈就完事了,值得一说的是加速代码,暂时没找到什么空间复杂度很低的算法。

参考资料:https://blog.csdn.net/yujuan_mao/article/details/8119529

取消标准输入输出的同步,可以加速输入三倍(因为cin太慢啦),关掉cin和stdin的同步后,再把cin和cout的绑定也取消掉。瞬间提速……

static int x = [](){
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return NULL;
}(); class MinStack {
private:
stack<int> data;
stack<int> min_stack;
public:
/** initialize your data structure here. */
MinStack() = default; void push(int x) {
data.push(x);
if (min_stack.empty() || min_stack.top() >= x) {
min_stack.push(x);
}
} void pop() {
if (data.top() == min_stack.top()) {
min_stack.pop();
}
data.pop();
} int top() {
return data.top();
} int getMin() {
return min_stack.top();
}
};

运行结果

Runtime: 28 ms, faster than 98.82% of C++ online submissions for Min Stack.
Memory Usage: 17.2 MB, less than 12.90% of C++ online submissions for Min Stack.

最新文章

  1. ibatis XML标签的含义
  2. VC++编程中为程序加入启动画面功能
  3. SQL查询数据库信息, 数据库表名, 数据库表信息
  4. dubbo spring2.5.6与spring 3冲突解决
  5. Activity内部Handler引起内存泄露的原因分析
  6. Visual Studio Code使用typings拓展自动补全功能
  7. sql management studio 附加mdf文件出错的解决办法
  8. elk 添加节点
  9. 好大滴坑, Spring MVC覆盖了Trsaction
  10. Java 编程 订单、支付、退款、发货、退货等编号主动生成类
  11. 中文代码示例之Angular入门教程尝试
  12. 【52】java多线程剖析
  13. pytorch安装(使用pip3装到conda环境下)
  14. .NET常用功能
  15. MySQL 的几种进入方式
  16. FindExecutable:查找与一个指定文件关联在一起的程序的文件名
  17. 遍历 JSON JavaScript 对象树中的所有节点
  18. win7下配置IIS
  19. &quot;我们分手吧。&quot;女的对男的说。 &quot;为什么呢?亲爱的,你不要我了么?&quot; &quot;因为你幼稚。&quot;女的坚定地语气回答道,然后转身准备走。 男的上前踩住女的影子,然后说...
  20. python Django html 一对多数据实例 模态对话框添加数据

热门文章

  1. [LeetCode] 114. Flatten Binary Tree to Linked List 将二叉树展平为链表
  2. shell语法学习
  3. idea的groovy设置
  4. MinGW离线安装
  5. [转帖]PC虚拟化主流:KVM、XEN、OpenVZ详解
  6. 48 容器(七)——HashMap底层:哈希表结构与哈希算法
  7. golang面对接口
  8. Fiddler代理手机抓包
  9. HTML学习--基础知识
  10. gradle中引用本地项目