2021.4.2写给自己看

今天做了leetcode的第42题,问题是:
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
菜鸟的问题就是一编程教会遇到很多奇奇怪怪的问题。
首先思路都想不清楚,后来看教程说是要动态规划来处理。想着知道了方法来写程序,总应该没有那么多困难了吧。
于是写出来程序如下:

class Solution {
public:
    int trap(vector<int>& height) {
       
        int n = height.size();
        int i,j;
        long int maxwater=0;
        int left_max[n];
        int right_max[n];
        left_max[0] =hight[0];
        right_max[n-1] =hight[n-1];
        for (j = n-2; j>=0; j--)
        {
            if (right_max[j+1] < height[j])
                right_max[j] = height[j];
            else
                right_max[j] = right_max[j+1];
        }
        maxwater = maxwater + min(left_max[0],right_max[0]) - height[0];
        for (i = 1 ;i<n;i++)
        {
            if (left_max[i-1] < height[i])
                left_max[i] = height[i];
            else
                left_max[i] = left_max[i-1];
            maxwater = maxwater + min(left_max[i],right_max[i]) - height[i];
        }
        return maxwater;
    }
};

测试运行没有问题,一提交就有两个bug。
Char 22: runtime error: variable length array bound evaluates to non-positive value 0 (solution.cpp)
runtime error: reference binding to null pointer of type ‘int’ (stl_vector.h)
代码的鲁棒性还不够,没有考虑到 n=0 时候的情况,所以在只要处理n=0的时候就好了。
if (n == 0)
return 0;

class Solution {
public:
    int trap(vector<int>& height) {
       
        int n = height.size();
        if (n == 0)
            return 0;
        int i,j;
        long int maxwater=0;
        vector<int> left_max=height;
        vector<int> right_max=height;
        
        for (j = n-2; j>=0; j--)
        {
            if (right_max[j+1] < height[j])
                right_max[j] = height[j];
            else
                right_max[j] = right_max[j+1];
        }
        maxwater = maxwater + min(left_max[0],right_max[0]) - height[0];
        for (i = 1 ;i<n;i++)
        {
            if (left_max[i-1] < height[i])
                left_max[i] = height[i];
            else
                left_max[i] = left_max[i-1];
            maxwater = maxwater + min(left_max[i],right_max[i]) - height[i];
        }
        return maxwater;
    }
};

路长且阻,加油吧。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值