mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-04 15:01:35 +00:00
chefyuan
This commit is contained in:
62
animation-simulation/单调队列单调栈/leetcode739每日温度.md
Normal file
62
animation-simulation/单调队列单调栈/leetcode739每日温度.md
Normal file
@@ -0,0 +1,62 @@
|
||||
### leetcode 739 每日温度
|
||||
|
||||
题目描述:
|
||||
|
||||
> 请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。
|
||||
|
||||
示例1:
|
||||
|
||||
> 输入: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
|
||||
>
|
||||
> 输出:arr = [1, 1, 4, 2, 1, 1, 0, 0]
|
||||
|
||||
示例2:
|
||||
|
||||
> 输入:temperatures = [30,30,31,45,31,34,56]
|
||||
>
|
||||
> 输出:arr = [2,1,1,3,1,1,0]
|
||||
|
||||
#### 题目解析
|
||||
|
||||
其实我们可以换种方式理解这个题目,比如我们 temperatures[0] = 30,则我们需要找到后面第一个比 30 大的数,也就是 31,31的下标为 2,30 的下标为 0 ,则我们的返回数组 arr[0] = 2。
|
||||
|
||||
理解了题目之后我们来说一下解题思路。
|
||||
|
||||
遍历数组,数组中的值为待入栈元素,待入栈元素入栈时会先跟栈顶元素进行对比,如果小于该值则入栈,如果大于则将栈顶元素出栈,新的元素入栈。
|
||||
|
||||
例如栈顶为69,新的元素为72,则69出栈,72入栈。并赋值给 arr,69 的索引为4,72的索引为5,则 arr[4] = 5 - 4 = 1,这个题目用到的是单调栈的思想,下面我们来看一下视频解析。
|
||||
|
||||
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
注:栈中的括号内的值,代表索引对应的元素,我们的入栈的为索引值,为了便于理解将其对应的值写在了括号中
|
||||
|
||||
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public int[] dailyTemperatures(int[] T) {
|
||||
int len = T.length;
|
||||
if (len == 0) {
|
||||
return T;
|
||||
}
|
||||
Stack<Integer> stack = new Stack<>();
|
||||
int[] arr = new int[len];
|
||||
int t = 0;
|
||||
for (int i = 0; i < len; i++) {
|
||||
//单调栈
|
||||
while (!stack.isEmpty() && T[i] > T[stack.peek()]){
|
||||
arr[stack.peek()] = i - stack.pop();
|
||||
}
|
||||
stack.push(i);
|
||||
}
|
||||
return arr;
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user