每日温度
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例 1:
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
示例 2:
输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]
示例 3:
输入: temperatures = [30,60,90]
输出: [1,1,0]
我的思路
使用数组的高阶方法网上思路
使用栈
我的思路
var dailyTemperatures = function (temperatures) {
let arr = []
for (let i in temperatures) {
if (i < temperatures.length - 1) {
let num = temperatures.filter((item, index) => index > i).findIndex(item => item > temperatures[i])
arr.push(num !== -1 ? num + 1 : 0)
} else {
arr.push(0)
}
}
return arr
};
讲解
就是根据下标,将这个 下标后面的所有元素 放在一个新数组中,然后找出 原数组这个下标对应的值 与 新数组中第一个满足条件的元素的下标 ,将它放到 arr 中即可,需要注意的是:下标不能是最后一位,因为根据题目可知,最后一天必定不会升温,所以肯定为 0
i < temperatures.length - 1: 不能到最后一位,因为最后一位后面没有元素
temperatures.filter((item, index) => index > i): 找出在当前元素后面的所有元素
findIndex(item => item > temperatures[i]): 找出满足条件的第一个元素的下标
arr.push(num !== -1 ? num + 1 : 0): 因为Array.findIndex()返回满足条件的第一个下标,找不到就返回 -1
网上思路
var dailyTemperatures = function (temperatures) {
const n = temperatures.length;
const answer = new Array(n).fill(0);
const stack = [];
for (let i = 0; i < n; i++) {
while (stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) {
console.log("aaa===>", stack, stack[stack.length - 1], temperatures[stack[stack.length - 1]])
const idx = stack.pop();
answer[idx] = i - idx;
}
stack.push(i);
}
return answer;
};
讲解
stack: 存储的是温度数组的索引,并且这些索引对应的温度是单调递减的。也就是说,栈顶的索引对应的温度是当前栈中最大的温度。
stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]: 判断当栈不为空且当前温度大于栈顶索引对应的温度
idx: 对应栈顶索引
总结
这个题目不是很难,但我没想到要使用栈来解决这个问题,下次重写的时候试试用栈重写一遍。