LeetCode 42 - 接雨水(动态规划)

题目链接icon-default.png?t=M276https://leetcode-cn.com/problems/trapping-rain-water/submissions/题目:

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.


思路:

一开始想先写一个暴力算法,但是发现连暴力算法都花了好长时间debug,原因是没有考虑特殊情况和理解题目含义。

后来想到了利用动态规划的思想,建立两个数组分别记录某个位置能储存水的最大体积,两个数组分别从左边和右边开始遍历得到。优化前对于每一个位置都向后进行判断,复杂度为O(n^2),优化后省略了这一个过程,只需要记录目前所遍历过的高度中最高的高度即可,复杂度为O(n)。

题解:

class Solution {
public:
    int trap(vector<int>& height) {
        int i,j, curmax=0;
        int len=height.size(), answer=0;
        vector<int> ltor(len,0);
        vector<int> rtol(len,0);
        for(i=0;i<len;i++){
            curmax=max(curmax,height[i]);
            ltor[i]=max(ltor[i],curmax-height[i]);
        }
        curmax=0;
        for(i=len-1;i>=0;i--){
            curmax=max(curmax,height[i]);
            rtol[i]=max(rtol[i],curmax-height[i]);
        }
`       
        /* counting answer and the checking part */
        for(int i=0;i<len;i++){
            cout<<rtol[i]<<' ';
            answer+=min(rtol[i],ltor[i]);   // answer是两个数组的交集部分
        }   cout<<endl;
        for(int i=0;i<len;i++)  cout<<ltor[i]<<' ';

        return answer;
    }
};

优化前的n^2 方法:

for(int i=0;i<len;i++){
            for(int j=i+1;j<len;j++){
                if(height[i]>height[j])
                    ltor[j]=max(ltor[j],height[i]-height[j]);
                else break;
            }
        }

        for(int i=len-1;i>=0;i--){
            for(int j=i-1;j>=0;j--){
                if(height[i]>height[j])
                    rtol[j]=max(rtol[j],height[i]-height[j]);
                else break;
            }
        }

总结:

一道看似简单的题目,却连暴力算法都花了很长时间都没写好,可见我的代码能力需要增强,要认真审题,同时注意到题目的细节要求。最后对于代码的优化也要下足功夫!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值