题解 | #接雨水问题#

//接雨水问题 
//第一种比较直观
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * max water
     * @param arr int整型vector the array
     * @return long长整型
     */
    long long maxWater(vector<int>& arr) {
        
        long long res =0;
        int n =arr.size();
        vector<int> left(n+1);
        vector<int> right(n+1);
        int l_max=0,r_max=0;
        for(int i=0;i<n;i++)
        {
            l_max=max(l_max,arr[i]);
            left[i]=l_max;
        }
        for(int i=n-1;i>=0;i--)
        {
            r_max=max(r_max,arr[i]);
            right[i]=r_max;
        }
        for(int i=0;i<n;i++)
        {
            res+=min(left[i],right[i])-arr[i];
        }
        return res;
    }
};
//接雨水问题 
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * max water
     * @param arr int整型vector the array
     * @return long长整型
     */
    long long maxWater(vector<int>& arr) {
        
        long long res =0;
        int n =arr.size();
        int l_h=arr[0],r_h=arr[n-1];
        int l=0,r=n-1;
        while(l<=r)
        {
            r_h=max(r_h,arr[r]);
            l_h=max(l_h,arr[l]);
            if(l_h<r_h)
            {
                res+= l_h-arr[l];
                l++;
            }
            else if(l_h>r_h)
            {
                res+= r_h-arr[r];
                r--;
            }
            else {
                res+= l_h-arr[l];
                l++;
                if(l<=r)
                {
                    res+= l_h-arr[r];
                }
            }

        }
        return res;
    }
};


全部评论

相关推荐

没hc还海面!呜呜,避雷
回收旧报纸:没有海面吧,我做完笔试有一个多月了,还没消息
点赞 评论 收藏
分享
阿武同学:基本信息保留前面三行,其他的可以全部删掉,邮箱最重要的你没写,主修课程精简到8个以内,实习里面2/3/4都是水内容的,非要写的话建议两到三句话,项目经历排版优化下,自我评价缩到三行
点赞 评论 收藏
分享
09-29 15:34
已编辑
北京航空航天大学 C++
做个有文化的流氓:结果是好的,过程不重要,而且你的offer太多了
软开人,秋招你打算投哪些...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务