[leetcode]739. Daily Temperatures
Analysis
跟爸妈一起旅游了一个礼拜,然后就回学校准备开学啦~—— [心塞,这么大了还是很讨厌开学]
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].
一开始用暴力解决,然后提交果然超时了,然后参考了一下大神们的解法~具体可以参考一下:https://blog.csdn.net/kakitgogogo/article/details/78794032
Implement
方法一(暴力,O(n*n))
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int len = temperatures.size();
vector<int> res;
for(int i=0; i<len; i++){
int cur = temperatures[i];
int cnt = 0;
bool flag = false;
for(int j=i+1; j<len; j++){
if(temperatures[j] > cur){
cnt++;
flag = true;
break;
}
cnt++;
}
if(flag)
res.push_back(cnt);
else
res.push_back(0);
}
return res;
}
};
方法二(O(n))
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int len = temperatures.size();
vector<int> res(len, 0);
if(len == 0)
return res;
stack<int> index;
for(int i=0; i<len; i++){
while(!index.empty() && temperatures[i] > temperatures[index.top()]){
res[index.top()] = i-index.top();
index.pop();
}
index.push(i);
}
return res;
}
};