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.分析
本身这道题不是很难,最容易想到的解法是:根据当前的温度,从下一个位置开始,依次遍历往后的温度,如果存在一项比当前的温度高,将两者的位置差保存下来;否则,保存0。但这种解法的时间复杂度为。所以,本题的难点就在于如何避免重复的扫描,我想到的解法是利用单调栈(里面的温度保证是递减的)将遍历到的温度保存在栈里面,当遍历下一个时,跟栈顶元素进行比较,如果大于栈顶温度,说明比栈顶温度大的就是该温度,将两者的位置差保存下来;如果不必栈顶温度大,说明不存在。
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T){
int n = T.size();
vector<int> res(n, 0);
stack< pair<int, int> > s; //栈中的温度是递减的
for (int i = 0; i < n; ++i){
while (!s.empty() && s.top().first < T[i]){ //跟栈顶温度比较,若大于,则当天即为栈顶温度的气温升高日期
int pos = s.top().second;
res[pos] = i - pos; //两者的位置差,即相隔的时间
s.pop();
}
s.push({T[i], i});
}
return res;
}
};
3.类似的题目
Next Greater Element II(本题的简化版)