-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDailyTemperature.java
More file actions
50 lines (40 loc) · 1013 Bytes
/
DailyTemperature.java
File metadata and controls
50 lines (40 loc) · 1013 Bytes
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
41
42
43
44
45
46
47
48
49
50
package com.duke.stack;
import java.util.Stack;
/**
* @author thakurde https://leetcode.com/problems/daily-temperatures/
*/
public class DailyTemperature {
public static int[] dailyTemperatures(int[] s) {
int len = s.length;
int[] output = new int[len];
Stack<Integer> st = new Stack<>();
int i = 0;
while (i < len) {
if (st.isEmpty()) {
st.push(i);
i++;
} else {
while (!st.isEmpty() && s[i] > s[st.peek()]) {
int popIndex = st.pop();
int day = i - popIndex;
output[popIndex] = day;
}
st.push(i);
i++;
}
}
if (!st.isEmpty()) {
int popIndex = st.pop();
output[popIndex] = 0;
}
return output;
}
public static void main(String[] args) {
int[] T = { 73, 74, 75, 71, 69, 72, 76, 73 };
int[] prediction = DailyTemperature.dailyTemperatures(T);
System.out.println("Prediction of next higher temperature: ");
for (int i : prediction) {
System.out.print(i + " ");
}
}
}