题目地址:

https://oj.leetcode.com/problems/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.

方法:

思路很简单。

维护两个栈,一个是数据栈正常进出;另一个最小栈的栈顶保存着当前数据栈中的最小值。

这么说可能看不太懂,举个例子吧。

数据栈中:9,9,3,4,4,4,5,3,3,10 其中10是栈顶。

最小栈中:9,9,3,3,3

push操作:

当前进入数据栈中的值小于等于最小栈栈顶的值的话,则也将该值压进最小栈,否则就只push数据栈。

pop操作:

如果当前数据栈栈顶的值等于最小栈栈顶的值,那么两个栈都弹值;否则只弹数据栈栈顶的值。

注意:C++中,如果使用vector,就会出现MLE错误。我换成stack就顺利过关。怀疑跟stack底层是个链表,而vector底层是动态增长数组有关。(剖析STL没看,SHIT,瞎猜一个)

全部AC代码:

class MinStack {
private:
stack<int> trueStk;
stack<int> minStk;
public:
void push(int x) {
trueStk.push(x);
if (minStk.size() == )
minStk.push(x);
else
{
int tmp = getMin();
if (x <= tmp)
minStk.push(x);
}
} void pop() {
int tmp = top();
trueStk.pop();
if (tmp == getMin())
minStk.pop();
} int top() {
return trueStk.top();
} int getMin() {
return minStk.top();
}
};

最新文章

  1. 在不知下面有几个元素的时候,要去除最后一个元素的下边框jquery代码
  2. java日期比较,日期计算
  3. Nuget程序包 使用log4net
  4. 【caffe-windows】 caffe-master 之 cifar10 超详细
  5. 【原创】【Android New Features】—— 关于ADT 17的BuildConfig.DEBUG
  6. j2ee学习笔记 Filter过滤器
  7. [bx]和loop指令
  8. [mysql]一次主从数据不一致的问题解决过程
  9. mix-blend-mode
  10. 【MongoDB】MongoDB环境配置
  11. HTML5 页面编辑API之Range对象
  12. 队列添加对象后,所有都变成相同的(bug)
  13. docker mysql8 注意
  14. php算法题2
  15. C# 启动外部程序的几种常用方法汇总
  16. java 基础之--反射详解
  17. np.hsplit()
  18. linux ctags
  19. sed你所不知道的语法
  20. Vue于React特性对比(二)

热门文章

  1. 【C语言天天练(二四)】内存分配
  2. How to convert `ctime` to `datetime` in Python? - Stack Overflow
  3. Uva - 11419 - SAM I AM
  4. Jquery节点遍历
  5. Android开发之模板模式初探
  6. android新浪分享实例
  7. 使用ILmerge合并Exe、Dll文件的帮助类
  8. mini2440驱动奇谭——ADC驱动与測试(动态挂载驱动)
  9. CSS selectors for Selenium with example,selenium IDE
  10. MySQL将表a中查询的数据插入到表b中