/
DailyTemperatures.java
38 lines (33 loc) · 1.08 KB
/
DailyTemperatures.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
// https://leetcode.com/problems/daily-temperatures
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<IndexedValue> stack = new Stack<>();
int n = temperatures.length, res[] = new int[n];
for (int i = 0; i < n; i++) {
if (stack.isEmpty()) {
stack.push(new IndexedValue(temperatures[i], i));
} else {
while (!stack.isEmpty()) {
if (temperatures[i] > stack.peek().value) {
IndexedValue iv = stack.pop();
res[iv.index] = i - iv.index;
} else {
break;
}
}
stack.push(new IndexedValue(temperatures[i], i));
}
}
return res;
}
class IndexedValue {
int value, index;
IndexedValue(int value, int index) {
this.value = value;
this.index = index;
}
public String toString() {
return "(" + value + ", " + index + ")";
}
}
}