补第十四周Leetcode算法博客
739. Daily Temperatures
Given a list of daily temperatures, produce a list 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 temperatures = [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].
题目的描述很简单,找出所有天数之后最邻近的温度更高的天数
一开始想了一个算法
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> warmlist;
for (int i = 0; i < temperatures.size(); i++) {
int iswarm = 1;
int j;
for (j = i + 1; j < temperatures.size(); j++) {
if (temperatures[i] < temperatures[j]) {
warmlist.push_back(iswarm);
break;
} else {
iswarm++;
if (j == temperatures.size() - 1) {
iswarm = 0;
warmlist.push_back(iswarm);
}
}
}
}
warmlist.push_back(0);
return warmlist;
}
};
这个结果的样例是可以过的,但是在之后复杂的case里面会出现超时的问题,这个算法的主题是要求我们使用Stack栈结构实现O(n)时间复杂度的算法,因此我们要重构算法
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int length = temperatures.size();
vector<int> warmlist(length, 0);
stack<pair<int, int>> stk; //temperature, position
for (int i = 0; i < temperatures.size() - 1; i++) {
if (temperatures[i] < temperatures[i+1]) {
warmlist[i] = 1;
while (!stk.empty() && temperatures[i+1] > stk.top().first) {
warmlist[stk.top().second] = i + 1 - stk.top().second;
stk.pop();
}
} else {
stk.push(make_pair(temperatures[i], i));
}
}
return warmlist;
}
};
这里的思路是,我们为了避免O(n^2)嵌套遍历两次vector,当我们找到下一天的温度不大于当天气温时,我们将当天的温度和日期存在一个栈结构中,因为在给定一天时,我们只关心里这天最近的之后的更温暖的日期,所以当我们找到一个更温暖的天气时,我们在从栈顶取出之前保存的气温来做比较
算法运行结果
这道题让我们意识到当算法正确但是有超时问题时,可以考虑用空间换时间。存储一些有效的信息。