题目
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map 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.
思路
我实现了两种方法,一种方法超时,一种方法AC。首先说下AC的思路:
我们可以用累积的方式来考虑,而不是用高度*宽度来计算面积。换句话说,我们只需要求每个柱状的面积之和(宽度为1)
从左到右进行搜索,分别保持左和右的最大高度,就像部分容器的单侧墙一样。固定较高的一边,从较低的部分开始补充水。例如,如果当前的左边的高度较低,我们就在左边的箱子里填满水,然后不断求和,一旦发现左边的高度大于右边,我们再从右边补充水直到我们把整个集装箱填满了。
我一开始是考虑从底部一层一层计算雨水的。但是超时了。
AC
class Solution {
public int trap(int[] height) {
int left=0,right = height.length-1;
int maxleft=0,maxright=0,res=0;
while(left<=right)
{
if(height[left]<=height[right])
{
if(height[left]>maxleft) maxleft = height[left];
else res+=maxleft-height[left];
left++;
}
else
{
if(height[right]>maxright) maxright = height[right];
else res+=maxright-height[right];
right--;
}
}
return res;
}
}
超时
class Solution {
public int trap(int[] height) {
//step 1 find max and min
int max =Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
if(height.length==0)
return 0;
for(int i=0;i<height.length;i++)
{
max = Math.max(max,height[i]);
min = Math.min(min,height[i]);
}
if(min==max)
return 0;
int res =0;
for(int i = min+1;i<=max;i++)
{
int[] index = findindex(height,i-1);
int front_index = index[0];
int back_index = index[1];
for(int j=front_index;j<=back_index;j++)
{
if(height[j]<i)
{
res++;
}
}
}
return res;
}
public int[] findindex(int[] height,int value){
//step2 find front index and back index(front >min ; back>min)
int[] index = new int[2];
int front_index = 0;
int back_index = 0;
for(int i=0;i<height.length;i++)
{
if(height[i]> value)
{
front_index = i;
break;
}
}
for(int i=height.length-1;i>=0;i--)
{
if(height[i]> value)
{
back_index = i;
break;
}
}
index[0] = front_index;
index[1] = back_index;
return index;
}
}