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