|
| 1 | +--- |
| 2 | +comments: true |
| 3 | +difficulty: medium |
| 4 | +# Follow `Topics` tags |
| 5 | +tags: |
| 6 | + - Array |
| 7 | + - Stack |
| 8 | + - Monotonic Stack |
| 9 | +--- |
| 10 | + |
| 11 | +# [739. Daily Temperatures](https://leetcode.com/problems/daily-temperatures/description/) |
| 12 | + |
| 13 | +## Description |
| 14 | + |
| 15 | +You're given an array of integers `temperatures`, where each element represents the temperature of a specific day. |
| 16 | +Return a new array `answer` such that `answer[i]` indicates how many days you must wait after the i-th day to experience a warmer temperature. |
| 17 | +If there’s no future day with a warmer temperature, set `answer[i]` to `0`. |
| 18 | + |
| 19 | +**Example 1:** |
| 20 | +``` |
| 21 | +Input: temperatures = [71,73,77,61,73,75,73] |
| 22 | +Output: [1,1,3,1,1,0,0] |
| 23 | +``` |
| 24 | + |
| 25 | +**Example 2:** |
| 26 | +``` |
| 27 | +Input: temperatures = [10,20,30] |
| 28 | +Output: [1,1,0] |
| 29 | +``` |
| 30 | + |
| 31 | +**Constraints:** |
| 32 | + |
| 33 | +* `1 <= n <= 8` |
| 34 | + |
| 35 | +## Solution |
| 36 | + |
| 37 | +We use a monotonic stack to track temperatures: |
| 38 | +1. Stack stores indices of temperatures in decreasing order |
| 39 | +2. When we find a warmer temperature, we pop indices from stack and calculate waiting days |
| 40 | +3. The waiting days are the difference between current index and popped index |
| 41 | +4. Any temperatures without a warmer day ahead remain in stack (result stays 0) |
| 42 | + |
| 43 | +```java |
| 44 | +class Solution { |
| 45 | + public int[] dailyTemperatures(int[] temperatures) { |
| 46 | + Stack<Integer> stack = new Stack<>(); |
| 47 | + int[] result = new int[temperatures.length]; |
| 48 | + for (int i = 0; i < temperatures.length; i++) { |
| 49 | + while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { |
| 50 | + int index = stack.pop(); |
| 51 | + result[index] = i - index; |
| 52 | + } |
| 53 | + stack.push(i); |
| 54 | + } |
| 55 | + |
| 56 | + return result; |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +```python |
| 62 | +class Solution: |
| 63 | + def dailyTemperatures(self, temperatures: list[int]) -> list[int]: |
| 64 | + stack = [] |
| 65 | + res = [0] * len(temperatures) |
| 66 | + for i, t in enumerate(temperatures): |
| 67 | + while stack and t > temperatures[stack[-1]]: |
| 68 | + idx = stack.pop() |
| 69 | + res[idx] = i - idx |
| 70 | + stack.append(i) |
| 71 | + return res |
| 72 | +``` |
| 73 | + |
| 74 | +## Complexity |
| 75 | + |
| 76 | +- Time complexity: $$O(n)$$ |
| 77 | +<!-- Add time complexity here, e.g. $$O(n)$$ --> |
| 78 | + |
| 79 | +- Space complexity: $$O(n)$$ |
| 80 | +<!-- Add space complexity here, e.g. $$O(n)$$ --> |
0 commit comments