Skip to content

Commit a4d34a9

Browse files
Create 739. 每日温度.md
1 parent 5de0fc0 commit a4d34a9

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

Monotonic Stack/739. 每日温度.md

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#### 739. 每日温度
2+
3+
难度:中等
4+
5+
---
6+
7+
给定一个整数数组 `temperatures` ,表示每天的温度,返回一个数组 `answer` ,其中 `answer[i]` 是指对于第 `i` 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 `0` 来代替。
8+
9+
**示例 1:**
10+
11+
```
12+
输入: temperatures = [73,74,75,71,69,72,76,73]
13+
输出: [1,1,4,2,1,1,0,0]
14+
```
15+
16+
**示例 2:**
17+
18+
```
19+
输入: temperatures = [30,40,50,60]
20+
输出: [1,1,1,0]
21+
```
22+
23+
**示例 3:**
24+
25+
```
26+
输入: temperatures = [30,60,90]
27+
输出: [1,1,0]
28+
```
29+
30+
**提示:**
31+
32+
* `1 <= temperatures.length <= 10^5`
33+
* `30 <= temperatures[i] <= 100`
34+
35+
---
36+
37+
方法一,动态规划 + 双指针:
38+
39+
从后向前遍历,在每个循环中会**跳过一定的区域**,思路类似于[这个](https://leetcode.cn/problems/daily-temperatures/solution/jie-ti-si-lu-by-pulsaryu/)
40+
41+
时间复杂度$O(N)$,空间复杂度$O(N)$。
42+
43+
![](https://raw.githubusercontent.com/CompetitiveLin/ImageHostingService/picgo/imgs/202304091057244.png)
44+
45+
```Java
46+
class Solution {
47+
public int[] dailyTemperatures(int[] temperatures) {
48+
int n = temperatures.length;
49+
int[] dp = new int[n];
50+
dp[n - 1] = 0;
51+
for(int i = n - 2; i >= 0; i--){
52+
int index = i + 1, cnt = 1;
53+
while(dp[index] != 0 && temperatures[index] <= temperatures[i]){
54+
cnt += dp[index];
55+
index += dp[index];
56+
}
57+
if(temperatures[index] <= temperatures[i]) dp[i] = 0;
58+
else dp[i] = cnt;
59+
}
60+
return dp;
61+
}
62+
}
63+
```
64+
65+
方法二,单调栈:
66+
67+
维护一个存储下标的单调栈,**从栈底到栈顶的下标对应的温度列表中的温度依次递减**。如果一个下标在单调栈里,则表示尚未找到下一次温度更高的下标。每次弹出栈中的元素(下标),都能得到该下标的答案(下一次温度更高的下标,为当前下标减去弹出元素的下标)。
68+
69+
```java
70+
class Solution {
71+
public int[] dailyTemperatures(int[] temperatures) {
72+
int n = temperatures.length;
73+
ArrayDeque<Integer> stack = new ArrayDeque<>();
74+
int[] ans = new int[n];
75+
for(int i = 0; i < n; i++){
76+
while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
77+
ans[stack.peek()] = i - stack.pop();
78+
}
79+
stack.push(i);
80+
}
81+
return ans;
82+
}
83+
}
84+
```
85+

0 commit comments

Comments
 (0)