刷题739. Daily Temperatures
Posted siweihz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了刷题739. Daily Temperatures相关的知识,希望对你有一定的参考价值。
一、题目说明
题目739. Daily Temperatures,返回一列数,改天要等多少天才能升温。难度是Medium!
二、我的解答
这个题目,用dp解决非常方便:
class Solution{
public:
vector<int> dailyTemperatures(vector<int>& T){
int len = T.size();
vector<int> dp(len,0);
dp[len-1] = 0;
for(int i=len-2;i>=0;i--){
if(T[i]<T[i+1]){
dp[i] = 1;
}else if(T[i]==T[i+1]){
if(dp[i+1]==0){
dp[i] = 0;
} else{
dp[i] = dp[i+1] + 1;
}
}else{
for(int j=i+2;j<len;j++){
if(T[i]<T[j]){
dp[i] = j-i;
break;
}
}
}
}
return dp;
}
};
性能如下:
Runtime: 664 ms, faster than 5.08% of C++ online submissions for Daily Temperatures.
Memory Usage: 14.7 MB, less than 100.00% of C++ online submissions for Daily Temperatures.
三、优化措施
用一个单调递增栈,可以减少比较的次数:
class Solution{
public:
//promte by stack
vector<int> dailyTemperatures(vector<int>& T){
int len = T.size();
vector<int> res(len,0);
stack<int> st;
for(int i=0;i<len;i++){
while(! st.empty() && T[st.top()]<T[i]){
res[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
return res;
}
};
性能如下:
Runtime: 188 ms, faster than 90.99% of C++ online submissions for Daily Temperatures.
Memory Usage: 16.1 MB, less than 68.00% of C++ online submissions for Daily Temperatures.
以上是关于刷题739. Daily Temperatures的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode739 Daily Temperatures
739. Daily Temperatures - LeetCode
[栈] leetcode 739 Daily Temperatures
LeetCode 739:每日温度 Daily Temperatures