Back to Stack
Medium
Daily Temperatures
Given an array of integers `temperatures` represents the daily temperatures, return an array `answer` such that `answer[i]` is the number of days you have to wait after the `i`th day to get a warmer temperature. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
Examples
Input:temperatures = [73,74,75,71,69,72,76,73]
Output:[1,1,4,2,1,1,0,0]
For day 0 (73), it takes 1 day to reach 74. For day 2 (75), it takes 4 days to reach 76.
Input:temperatures = [30,40,50,60]
Output:[1,1,1,0]
Each day is warmer than the previous.
Constraints
1 <= temperatures.length <= 10^530 <= temperatures[i] <= 100
Approach
For each day, iterate through the subsequent days to find the first day with a higher temperature. Keep track of the number of days waited. If no warmer day is found, the answer for that day is 0.
Complexity Analysis
Time Complexity
O(n^2)
Space Complexity
O(1)
This will likely cause a Time Limit Exceeded (TLE) error for large arrays.
Solution.java
class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (temperatures[j] > temperatures[i]) { result[i] = j - i; break; } } } return result; }}