739. 每日温度

 1 import java.util.Stack;
 2 
 3 public class DailyTemperatures {
 4     public int[] dailyTemperatures(int[] T) {
 5         Stack<Integer> stack = new Stack<>();
 6         int[] res = new int[T.length];
 7         for(int i = T.length - 1; i >= 0; i--) {
 8             if(stack.isEmpty()) {
 9                 stack.push(i);
10                 res[i] = 0;
11             }else {
12                 if(T[i] < T[stack.peek()]) {
13                     res[i] = stack.peek() - i;
14                     stack.push(i);
15                 }else {
16                     
17                     //实际上for循坏内只需要保留该段代码即可
18                     while(!stack.isEmpty() && T[stack.peek()] <= T[i]) {
19                         stack.pop();
20                     }
21                     if(stack.isEmpty()) {
22                         res[i] = 0;
23                     }else {
24                         res[i] = stack.peek() - i;
25                     }
26                     stack.push(i);
27                     
28                 }
29             }           
30         }
31         return res;
32     }    
33 }

根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/daily-temperatures

猜你喜欢

转载自www.cnblogs.com/xiyangchen/p/11204615.html