From 82ab1706f88e390ff2f13478cd7771cc92e76754 Mon Sep 17 00:00:00 2001 From: Jamcy123 <1219502823@qq.com> Date: Tue, 12 Apr 2022 17:09:20 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=89=88=E6=9C=AC=E4=B8=80?= =?UTF-8?q?=E3=80=81=E5=A2=9E=E5=8A=A0=E7=89=88=E6=9C=AC=E4=BA=8C=200739.?= =?UTF-8?q?=E6=AF=8F=E6=97=A5=E6=B8=A9=E5=BA=A6=20javascript=20=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0739.每日温度.md | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) 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; +}; ```