[LeetCode] Daily Temperatures

739. Daily Temperatures

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
vector<int> st;
vector<int> res(T.size(), 0);
for(int i = T.size() - 1; i >= 0; i--) {
while(!st.empty() and T[st.back()] <= T[i]) st.pop_back();
if(!st.empty()) {
res[i] = st.back() - i;
}
st.push_back(i);
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
int n = T.size();
vector<int> res(n, 0);
map<int, int> m;
for(int i = n - 1; i >= 0; i--) {
auto it = m.upper_bound(T[i]);
if(it != end(m)) res[i] = it->second - i;
m[T[i]] = i;
it = m.find(T[i]);
do if(it != begin(m)){
it = prev(it);
it->second = i;
}while(it != begin(m));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/05/PS/LeetCode/daily-temperatures/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.