LintCode363.接雨水
阿新 • • 發佈:2018-12-23
題目連結
超時程式碼:
class Solution {
public:
/**
* @param heights: a list of integers
* @return: a integer
*/
int trapRainWater(vector<int> &heights) {
// write your code here
int sum=0;
if(!heights.empty())
{
int max=heights[0],temp, i,j,k;//max為向量中的最大值
for(int i=1;i<heights.size();i++)
{
if(heights[i]>max)
{
max=heights[i];
}
}
for(i=0;i<max;i++)
{
for(j=0;j<heights.size();j++)
{
if(heights[j]>0)
{
temp=0;
for(k=j+1;k<heights.size();k++)
{
if(heights[k]<=0)
{
temp++;
}
else
{
sum+=temp;
break;
}
}
}
heights[j]--;
}
}
}
return sum;
}
};
一千多毫秒
主要想法是一層一層的數
優化程式碼
int trapRainWater(vector<int> &heights) {
// write your code here
int sum=0;
if(!heights.empty())
{
int max=heights[0],maxIndex=0,size=heights.size(),X;//max為向量中的最大值
for(int i=1;i<size;i++)
{
if(heights[i]>max)
{
max=heights[i];
maxIndex = i;
}
}
cout<<max<<" "<<maxIndex<<endl;
X = heights[0];
for(int i=1;i<maxIndex;i++)
{
if(X < heights[i]) X = heights[i];
else sum+=(X-heights[i]);
}
X = heights[size-1];
for(int i=size-2;i>maxIndex;i--)
{
if(X<heights[i]) X=heights[i];
else sum+=(X-heights[i]);
}
}
return sum;
}
才50多毫秒
以前我覺得程式碼超時是一些需要“優化”而已,但是也許程式碼超時就是演算法錯了,優化也許就是換種思路而最優解。
- 超時程式碼是一層一層的數,LintCode給出資料有3層12個,意味著你至少算3×12次,實際更多
- 優化程式碼從橫向解決問題,它最多隻會算12次,所以大大減少了時間,而且程式碼也不那麼雜亂了。
- 以後超時一定多想是不是思路、角度、方法的問題,往往就是這些原因導致的超時