博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - Min Stack
阅读量:4611 次
发布时间:2019-06-09

本文共 1335 字,大约阅读时间需要 4 分钟。

2015.1.23 12:13

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.

Solution:

  This could almost be counted as a FAQ. You'll find a same question in "Cracking the Coding Interview". A min stack is maintained alongside the data stack, recording every minimal (so far) element. The min stack is updated whever a new minimal value is being pushed, or the current minimal value is being popped.

  Total time complexity for each operation is strictly O(1). Extra space of O(n) is required to maintain the min stack.

Accepted code:

1 // 1AC, old 2 #include 
3 using namespace std; 4 5 class MinStack { 6 public: 7 void push(int x) { 8 if (ms.empty() || ms.top() >= x) { 9 ms.push(x);10 }11 s.push(x);12 }13 14 void pop() {15 if (s.top() == ms.top()) {16 ms.pop();17 }18 s.pop();19 }20 21 int top() {22 return s.top();23 }24 25 int getMin() {26 return ms.top();27 }28 private:29 stack
s, ms;30 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/4243876.html

你可能感兴趣的文章
swoolefy PHP的异步、并行、高性能网络通信引擎内置了Http/WebSocket服务器端/客户端...
查看>>
Python学习笔记
查看>>
unshift()与shift()
查看>>
使用 NPOI 、aspose实现execl模板公式计算
查看>>
行为型模式:中介者模式
查看>>
How to Notify Command to evaluate in mvvmlight
查看>>
33. Search in Rotated Sorted Array
查看>>
461. Hamming Distance
查看>>
Python垃圾回收机制详解
查看>>
jquery 编程的最佳实践
查看>>
MeetMe
查看>>
IP报文格式及各字段意义
查看>>
(转载)rabbitmq与springboot的安装与集成
查看>>
C2. Power Transmission (Hard Edition)(线段相交)
查看>>
STM32F0使用LL库实现SHT70通讯
查看>>
Atitit. Xss 漏洞的原理and应用xss木马
查看>>
MySQL源码 数据结构array
查看>>
(文件过多时)删除目录下全部文件
查看>>
T-SQL函数总结
查看>>
python 序列:列表
查看>>