标签:sub -- ssi ons ret memory fast runtime fas
一、题目说明
题目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.
标签:sub -- ssi ons ret memory fast runtime fas
原文地址:https://www.cnblogs.com/siweihz/p/12304692.html