forked from azl397985856/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path739.daily-temperatures.js
More file actions
42 lines (38 loc) · 911 Bytes
/
739.daily-temperatures.js
File metadata and controls
42 lines (38 loc) · 911 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* @lc app=leetcode id=739 lang=javascript
*
* [739] Daily Temperatures
*/
/**
* @param {number[]} T
* @return {number[]}
*/
var dailyTemperatures = function(T) {
// // 暴力 时间复杂度O(n^2), 空间复杂度O(1)
// const res = [];
// for(let i = 0; i < T.length; i++) {
// res[i] = 0;
// for(let j = i; j < T.length; j++) {
// if (T[j] > T[i]) {
// res[i] = j - i;
// break;
// }
// }
// }
// return res;
// 递增栈/递减栈
// 这里我们需要用到递减栈
// 时间复杂度O(n), 空间复杂度O(n)
// 典型的空间换时间
const stack = [];
const res = [];
for (let i = 0; i < T.length; i++) {
res[i] = 0;
while (stack.length !== 0 && T[i] > T[stack[stack.length - 1]]) {
const peek = stack.pop();
res[peek] = i - peek;
}
stack.push(i);
}
return res;
};