每日温度
LeetCode739-每日温度(单调栈)
#resource / algorithm
#type / snippet
#status / evergreen
#source / leetcode
#algo / monotonic-stack
#ds / stack
[!info] related notes 算法面试题型 MOC 单调栈
每日温度
题目
题解
从右往左依次将温度压入单调栈,压入前,抛出所有更低温度的数据(保持单调栈单调),获取下一个升温的下标(减去当前下标,即可获得几天后升温)
var dailyTemperatures = function(temperatures) {
const n = temperatures.length;
const ans = Array(n).fill(0);
const st = [];
for (let i = n-1;i>=0;i--) {
const t = temperatures[i];
while(st.length && t >= temperatures[st[st.length-1]]) {
st.pop();
}
if (st.length) {
ans[i] = st[st.length - 1] - i;
}
st.push(i);
}
return ans;
};