leetcode-master/problems/0901.股票价格跨度.md

40 lines
1.2 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.

这道题也不是单调栈的简单题
需要记录 传入的所有price
注意 股票价格相同的情况
需要自己维护一个数组用stack来记录下表 因为数组下标从0开始的注意 栈为空的两种情况(代码中注释)。
如果这道题,不用这个应用场景,而是直接给出输入数组的话,会简单一些。
这道题目他们都用两个栈来实现,貌似代码简介一些,但我这个最直观。 可以画一个图
```
class StockSpanner {
public:
stack<int> st;
vector<int> prices;
StockSpanner() {
}
int next(int price) {
prices.push_back(price);
while (!st.empty() && prices[st.top()] <= price) { // 注意这里等于的情况
st.pop();
}
int result;
int curPriceIndex = prices.size() - 1;
if (!st.empty()) { // 栈不为空,求差值
result = curPriceIndex - st.top();
} else { // 栈为空
if (prices.size() == 1) result = 1; // 如果是放入第一个元素就是result是1
else result = curPriceIndex + 1; // 不是放入的第一个元素了,那么就应该是当前索引+1
}
st.push(curPriceIndex);
return result;
}
};
```