关于网上最小栈解法的疑问

2018-02-28 13:42:02 +08:00
 zl939144892
先上链接 https://www.cnblogs.com/loveyixiang/p/6030920.html
邮个疑问: 就是当 B 栈的数据先出完了,再怎么获取最小值呢?
2342 次点击
所在节点    算法
3 条回复
ai277014717
2018-02-28 16:50:40 +08:00
B 不会出完,保证 B 跟 A 栈元素个数一样。当初的面试题啊,一脸蒙蔽
ai277014717
2018-02-28 17:11:26 +08:00
`class MinStack {
public:
/** initialize your data structure here. */
stack<int> sta;
stack<int> stb;
MinStack() {

}

void push(int x) {
sta.push(x);
if(stb.size()==0){
stb.push(x);
}
else {
if(stb.top()>x){
stb.push(x);
}
else {
stb.push(stb.top());
}
}
}

void pop() {
sta.pop();
stb.pop();
}

int top() {
return sta.top();
}

int getMin() {
return stb.top();
}
};`
刚刚水了一题
ai277014717
2018-02-28 17:18:36 +08:00
```
class MinStack {
public:
/** initialize your data structure here. */
stack<int> sta;
stack<int> stb;
MinStack() {

}

void push(int x) {
sta.push(x);
if(stb.size()==0){
stb.push(x);
}
else {
if(stb.top()>x){
stb.push(x);
}
else {
stb.push(stb.top());
}
}
}

void pop() {
sta.pop();
stb.pop();
}

int top() {
return sta.top();
}

int getMin() {
return stb.top();
}
};
```
试试 markdown

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/433466

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX