今天做了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;
}
};
路长且阻,加油吧。