LeetCode75| 单调栈
•
算法结构
目录
739 每日温度
901 股票价格跨度
739 每日温度
求后面第一个比他大的元素的位置,单调栈需要递增
求后面第一个比他小的元素的位置,单调栈需要递减
本题栈头到栈底的顺序应该从小到大
class Solution {
public:
vector dailyTemperatures(vector& temperatures) {
stackst;
vectorres(temperatures.size());
st.push(0);
for(int i = 1;i < temperatures.size();i++){
if(temperatures[i] temperatures[st.top()]){
res[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
}
return res;
}
};
时间复杂度O(n)
空间复杂度O(n)
901 股票价格跨度
求后面第一个比他大的元素的位置,单调栈需要递增
求后面第一个比他小的元素的位置,单调栈需要递减
本题栈头到栈底的顺序应该从大到小
注意插入一个日期为-1,价格为INT_MAX的值,确保栈不会为空
class StockSpanner {
public:
StockSpanner() {
this->st.emplace(-1,INT_MAX);
this->idx = -1;
}
int next(int price) {
idx++;
while(st.top().second <= price){
st.pop();
}
int res = idx - st.top().first;
st.emplace(idx,price);
return res;
}
private:
stack<pair>st;
int idx;
};
时间复杂度O(n)
空间复杂度O(n)
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/fc81cfc9c6.html
