Leetcode 739. Daily Temperatures
You are 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, put 0
instead.
temperatures
array to be empty?
temperatures
array)?
To solve this problem efficiently, we can use a stack to keep track of the indices of the temperature array. By iterating through the array once, we push the indices onto the stack when the current day’s temperature is not warmer than the temperature at the index on the top of the stack. When we find a day that is warmer, we calculate the difference between the current index and the index on the top of the stack. We then update our answer array accordingly and continue.
Here’s how we can do it:
temperatures
.#include <vector>
#include <stack>
std::vector<int> dailyTemperatures(std::vector<int> &temperatures) {
int n = temperatures.size();
std::vector<int> answer(n, 0);
std::stack<int> indices; // stack to store indices of temperatures
for (int i = 0; i < n; ++i) {
while (!indices.empty() && temperatures[i] > temperatures[indices.top()]) {
int idx = indices.top();
indices.pop();
answer[idx] = i - idx;
}
indices.push(i);
}
return answer;
}
The time complexity of this solution is (O(n)), where (n) is the number of days (or the length of the temperatures
array). Each element is pushed and popped from the stack at most once, making the overall time complexity linear.
The space complexity is (O(n)) due to the use of the stack which stores indices of temperatures and the answer
array which holds the result.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?