Fork me on GitHub

包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:

void push(int x) {
s1.push(x);
if(s2.empty() || x <= s2.top())
{
s2.push(x);
}
}
void pop() {
if(s1.top() == s2.top())
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int min() {
return s2.top();
}
private:
stack<int> s1,s2;
};

本文标题:包含min函数的栈

文章作者:LiuXiaoKun

发布时间:2019年02月20日 - 22:02

最后更新:2019年02月20日 - 22:02

原始链接:https://LiuZiQiao.github.io/2019/02/20/包含min函数的栈/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%