-
Notifications
You must be signed in to change notification settings - Fork 0
/
DailyTemp.java
40 lines (37 loc) · 1.08 KB
/
DailyTemp.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package org.sean.stack;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
/***
* 739. Daily Temperatures
*/
public class DailyTemp {
public int[] dailyTemperatures(int[] temperatures) {
int len = temperatures.length;
if (len == 0)
return new int[]{0};
int[] res = new int[len];
Deque<Integer> stack = new ArrayDeque<>();
int i = 0;
while (i < len) {
int elem = temperatures[i];
if (stack.isEmpty() || temperatures[stack.peek()] >= elem) {
stack.push(i);
} else { // < elem
while (!stack.isEmpty()) {
int index = stack.peek();
if(temperatures[index] < elem) {
res[index] = i - index;
stack.pop();
} else {
break;
}
}
stack.push(i);
}
i++;
}
// System.out.println(Arrays.toString(res));
return res;
}
}