algorithm-base/animation-simulation/单调队列单调栈/leetcode739每日温度.md

83 lines
3.3 KiB
Java
Raw Normal View History

2021-07-23 15:44:19 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
2021-03-20 11:38:55 +00:00
>
>
>
2021-07-23 15:44:19 +00:00
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 11:38:55 +00:00
#### [739. ](https://leetcode-cn.com/problems/daily-temperatures/)
2021-03-19 08:36:59 +00:00
> 0
2021-07-23 15:44:19 +00:00
1
2021-03-19 08:36:59 +00:00
> temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
>
2021-07-23 15:44:19 +00:00
> arr = [1, 1, 4, 2, 1, 1, 0, 0]
2021-03-19 08:36:59 +00:00
2021-07-23 15:44:19 +00:00
2
2021-03-19 08:36:59 +00:00
> temperatures = [30,30,31,45,31,34,56]
>
2021-07-23 15:44:19 +00:00
> arr = [2,1,1,3,1,1,0]
2021-03-19 08:36:59 +00:00
####
2021-07-23 15:44:19 +00:00
temperatures[0] = 30, 30 3131 230 0 arr[0] = 2
2021-03-19 08:36:59 +00:00
2021-07-23 15:44:19 +00:00
69 72 69 72 arr69 472 5 arr[4] = 5 - 4 = 1
2021-03-19 08:36:59 +00:00
![](https://img-blog.csdnimg.cn/20210319163137996.gif)
便
```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()]){
2021-07-23 15:44:19 +00:00
arr[stack.peek()] = i - stack.pop();
}
2021-03-19 08:36:59 +00:00
stack.push(i);
}
return arr;
}
}
```
2021-07-27 18:26:32 +00:00
GO Code:
```go
func dailyTemperatures(temperatures []int) []int {
l := len(temperatures)
if l == 0 {
return temperatures
}
stack := []int{}
arr := make([]int, l)
for i := 0; i < l; i++ {
for len(stack) != 0 && temperatures[i] > temperatures[stack[len(stack) - 1]] {
idx := stack[len(stack) - 1]
arr[idx] = i - idx
stack = stack[: len(stack) - 1]
}
// 栈保存的是索引
stack = append(stack, i)
}
return arr
}