-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDaily Temperature.java
41 lines (32 loc) · 1.12 KB
/
Daily Temperature.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
41
// https://leetcode.com/problems/daily-temperatures/
// https://youtu.be/cTBiBSnjO3c?si=83SNP0LT1tt30kro
//
// IMPORTANT: The solution requires knowing what a monotonic stack is and how it works.
/*
Time Complexity: O(n) where n = length of temperatures
Space Complexity: O(n) where n = length of stack
*/
class Node {
int val;
int idx;
}
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] res = new int[temperatures.length];
Arrays.fill(res, 0);
Stack<Node> tmpStack = new Stack<>();
for (int i = 0; i < temperatures.length; i++) {
Node newNode = new Node();
newNode.val = temperatures[i];
newNode.idx = i;
// If stack isn't empty and top of stack's temperature is less than ith day's weather,
// pop stack and update return array at head's index
while (!tmpStack.empty() && newNode.val > tmpStack.peek().val) {
Node head = tmpStack.pop();
res[head.idx] = i - head.idx;
}
tmpStack.push(newNode);
}
return res;
}
}