Min Stack leetcode
2016-01-03 21:32
435 查看
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.
使用一个栈,和一个保存最小值的变量min
栈中保存的元素是 新加数和当前min的差,然后更新min,使min保持最小
利用差值使每个栈元素可以包含两个信息量
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.
使用一个栈,和一个保存最小值的变量min
栈中保存的元素是 新加数和当前min的差,然后更新min,使min保持最小
利用差值使每个栈元素可以包含两个信息量
class MinStack { public: void push(int x) { if (sta.empty()) { sta.push(0); min = x; } else { sta.push(x - min); if (x < min) min = x; } } void pop() { if (sta.empty()) return; long top = sta.top(); if (top < 0) min = min - top; sta.pop(); } int top() { if (sta.empty()) return 0; long top = sta.top(); if (top < 0) return min; else return min + top; } int getMin() { return min; } private: stack<long> sta; long min; };
相关文章推荐
- bzoj 1089 [SCOI2003]严格n元树(DP+高精度)
- Ubuntu配置静态ip
- caffe的Leveldb格式数据四(实例)
- 日本恐怖片《二重身》核心内容赏析
- 以前的博客
- 使用AlertDialog创建对话框
- js'中的apply和call和bind的用法
- STM32的位带操作
- Hadoop完全分布式安装实战
- 数据库第二章
- 001Two Sum (C)
- <Java>函数的参数是数组
- 2015年终总结
- 深入了解View的绘制流程
- 遗传算法解决旅行商问题(TSP)
- js'中的apply和call和bind的用法
- KVC和KVO
- 详解CSS float属性
- 反序输出正整数和求数组交集的问题
- Introduction to the SQL Server Analysis Services Logistic Regression Data Mining Algorithm