Skip to content

Commit 82ab170

Browse files
committed
修改版本一、增加版本二 0739.每日温度 javascript 版本
1 parent ae38a29 commit 82ab170

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

problems/0739.每日温度.md

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -301,32 +301,46 @@ func dailyTemperatures(num []int) []int {
301301

302302
JavaScript:
303303
```javascript
304-
/**
305-
* @param {number[]} temperatures
306-
* @return {number[]}
307-
*/
304+
// 版本一
308305
var dailyTemperatures = function(temperatures) {
309-
let n = temperatures.length;
310-
let res = new Array(n).fill(0);
311-
let stack = []; // 递减栈:用于存储元素右面第一个比他大的元素下标
306+
const n = temperatures.length;
307+
const res = Array(n).fill(0);
308+
const stack = []; // 递增栈:用于存储元素右面第一个比他大的元素下标
312309
stack.push(0);
313310
for (let i = 1; i < n; i++) {
314311
// 栈顶元素
315-
let top = stack[stack.length - 1];
312+
const top = stack[stack.length - 1];
316313
if (temperatures[i] < temperatures[top]) {
317314
stack.push(i);
318315
} else if (temperatures[i] === temperatures[top]) {
319316
stack.push(i);
320317
} else {
321318
while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) {
322-
let top = stack.pop();
319+
const top = stack.pop();
323320
res[top] = i - top;
324321
}
325322
stack.push(i);
326323
}
327324
}
328325
return res;
329326
};
327+
328+
329+
// 版本二
330+
var dailyTemperatures = function(temperatures) {
331+
const n = temperatures.length;
332+
const res = Array(n).fill(0);
333+
const stack = []; // 递增栈:用于存储元素右面第一个比他大的元素下标
334+
stack.push(0);
335+
for (let i = 1; i < n; i++) {
336+
while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) {
337+
const top = stack.pop();
338+
res[top] = i - top;
339+
}
340+
stack.push(i);
341+
}
342+
return res;
343+
};
330344
```
331345

332346

0 commit comments

Comments
 (0)