修改版本一、增加版本二 0739.每日温度 javascript 版本

This commit is contained in:
Jamcy123
2022-04-12 17:09:20 +08:00
parent ae38a29068
commit 82ab1706f8

View File

@ -301,25 +301,22 @@ func dailyTemperatures(num []int) []int {
JavaScript JavaScript
```javascript ```javascript
/** // 版本一
* @param {number[]} temperatures
* @return {number[]}
*/
var dailyTemperatures = function(temperatures) { var dailyTemperatures = function(temperatures) {
let n = temperatures.length; const n = temperatures.length;
let res = new Array(n).fill(0); const res = Array(n).fill(0);
let stack = []; // 递栈:用于存储元素右面第一个比他大的元素下标 const stack = []; // 递栈:用于存储元素右面第一个比他大的元素下标
stack.push(0); stack.push(0);
for (let i = 1; i < n; i++) { for (let i = 1; i < n; i++) {
// 栈顶元素 // 栈顶元素
let top = stack[stack.length - 1]; const top = stack[stack.length - 1];
if (temperatures[i] < temperatures[top]) { if (temperatures[i] < temperatures[top]) {
stack.push(i); stack.push(i);
} else if (temperatures[i] === temperatures[top]) { } else if (temperatures[i] === temperatures[top]) {
stack.push(i); stack.push(i);
} else { } else {
while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) { while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) {
let top = stack.pop(); const top = stack.pop();
res[top] = i - top; res[top] = i - top;
} }
stack.push(i); stack.push(i);
@ -327,6 +324,23 @@ var dailyTemperatures = function(temperatures) {
} }
return res; 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;
};
``` ```