LintCode363.接雨水

题目链接
超时代码:

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次,所以大大减少了时间,而且代码也不那么杂乱了。
  • 以后超时一定多想是不是思路、角度、方法的问题,往往就是这些原因导致的超时

猜你喜欢

转载自blog.csdn.net/qq_42317011/article/details/85221705