739. 每日温度
1、暴力解法
var dailyTemperatures = function(temperatures) {
const res = [],len = temperatures.length;
for(let i=0; i<len; i++){
for(let j=i+1;j<len;j++){
// 找到大于的树,计算距离返回
if(temperatures[i] < temperatures[j]){
res.push(j-i)
break
}else if(temperatures[i] >= temperatures[j] && j == len-1){
res.push(0)
}
}
}
res.push(0)
return res
};
2、单调栈
通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,可以用单调栈。
var dailyTemperatures = function(temperatures) {
const n = temperatures.length;
const res = Array(n).fill(0);
const stack = []; // 递增栈:用于存储元素右面第一个比他大的元素下标
stack.push(0);
for (let i = 1; i < n; i++) {
// 栈顶元素,就是当前检查元素
const top = stack[stack.length - 1];
// 向后依次比较
if (temperatures[i] < temperatures[top]) {
stack.push(i);
} else if (temperatures[i] === temperatures[top]) {
stack.push(i);
} else {
while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) {
const top = stack.pop();
// 找到比当前值大的数,存放距离
res[top] = i - top;
}
stack.push(i);
}
}
return res;
};