Daily Temperatures

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

分析:

为了找到后面过了几天会有比当前值更大的值,所以,我们需要从尾遍历,我们用一个stack来存当前最大值。

 1 public class Solution {
 2     public int[] dailyTemperatures(int[] T) {
 3         if (T == null) return null;
 4         int[] result = new int[T.length];
 5         Stack<Temperature> stack = new Stack<>();
 6 
 7         for (int i = T.length - 1; i >= 0; i--) {
 8             if (stack.isEmpty()) {
 9                 result[i] = 0;
10                 stack.push(new Temperature(T[i], i));
11             } else if (stack.peek().value > T[i]) {
12                 result[i] = stack.peek().index - i;
13                 stack.push(new Temperature(T[i], i));
14             } else {
15                 while (!stack.isEmpty() && stack.peek().value <= T[i]) {
16                     stack.pop();
17                 }
18                 if (stack.isEmpty()) {
19                     result[i] = 0;
20                 } else {
21                     result[i] = stack.peek().index - i;
22                 }
23                 stack.push(new Temperature(T[i], i));
24             }
25         }
26         return result;
27     }
28 }
29 
30 class Temperature {
31     int value;
32     int index;
33 
34     public Temperature(int value, int index) {
35         this.value = value;
36         this.index = index;
37     }
38 }

 

posted @ 2019-08-01 13:56  北叶青藤  阅读(186)  评论(0)    收藏  举报