diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index 710f5eb6..5f53e412 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -301,25 +301,22 @@ func dailyTemperatures(num []int) []int { JavaScript: ```javascript -/** - * @param {number[]} temperatures - * @return {number[]} - */ +// 版本一 var dailyTemperatures = function(temperatures) { - let n = temperatures.length; - let res = new Array(n).fill(0); - let stack = []; // 递减栈:用于存储元素右面第一个比他大的元素下标 + const n = temperatures.length; + const res = Array(n).fill(0); + const stack = []; // 递增栈:用于存储元素右面第一个比他大的元素下标 stack.push(0); for (let i = 1; i < n; i++) { // 栈顶元素 - let top = stack[stack.length - 1]; + 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]]) { - let top = stack.pop(); + const top = stack.pop(); res[top] = i - top; } stack.push(i); @@ -327,6 +324,23 @@ var dailyTemperatures = function(temperatures) { } return res; }; + + +// 版本二 +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++) { + while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) { + const top = stack.pop(); + res[top] = i - top; + } + stack.push(i); + } + return res; +}; ```