leetcode-master/problems/0155.最小栈.md

52 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
https://leetcode-cn.com/problems/min-stack/
## 思路
有的同学一开始会把这道题目想简单了,用一个变量记录最小值不就得了,其实是如果要是弹出了这个最小值的话,我们还要记录次小值,所以需要一个辅助数组来记录次小值。
我这里使用数组来实现栈,在用一个数组来放当前栈里最小数值,同时使用辅助数组来记录
## C++代码
```
class MinStack {
public:
vector<int> vec;
vector<int> minVec;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
vec.push_back(x);
if (minVec.size() == 0) {
minVec.push_back(x);
} else if (x <= minVec[minVec.size() - 1]) { // 这里一定是下小于等于,防止多个最小值的情况
minVec.push_back(x);
}
}
void pop() {
if (vec.size() == 0) { // 防止下面的操作会导致越界
return;
}
if (vec[vec.size() - 1] == minVec[minVec.size() - 1]) {
minVec.pop_back();
}
vec.pop_back();
}
int top() {
// 这里有越界的危险但是题目也没有说如果栈为空top()应该返回啥所以就默认测试用例没有上来直接top的用例了
return vec[vec.size() - 1];
}
int getMin() {
// 这里有越界的危险但是题目也没有说如果栈为空getMin()应该返回啥所以就默认测试用例没有上来直接getMin的用例了
return minVec[minVec.size() - 1];
}
};
```
> 更过算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。