题目描述:
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.
起初用了一个非常笨的方法,在每一个水坑里找到左右两边最高的挡板,然后取最小值,得到体积。复杂度是O(n*n),超时了:
public int trap(int[] height) {
if(height.length<3)
return 0;
int sum=0;
for (int i = 1; i < height.length-1; i++) {
int leftIndex=i-1 , rightIndex=i+1;
int leftMaxHeight=0 , rightMaxHeight=0;
while(leftIndex>=0){
if(height[leftIndex]>leftMaxHeight)
leftMaxHeight=height[leftIndex];
leftIndex--;
}
while(rightIndex<=height.length-1){
if(height[rightIndex]>rightMaxHeight)
rightMaxHeight=height[rightIndex];
rightIndex++;
}
if(Integer.min(leftMaxHeight, rightMaxHeight)>height[i])
sum+=Integer.min(leftMaxHeight, rightMaxHeight)-height[i];
}
return sum;
}
后来联想到了前面的Container With Most Water,用两个指针得到了答案,从左右两边选取较小的边往中间靠拢。于是成功了,代码如下:
public int trap(int[] height) {
if(height.length<3)
return 0;
int sum=0;
int left=0,right=height.length-1;
//left表示左边最高高度的索引,right表示右边最高高度的索引
int i=left+1,j=right-1;
//遍历从1到height.length-2,计算每一个height[i]所盛水的体积
while(i<=j){
if(height[left]<=height[right]){
if(height[i]<height[left]){
sum+=height[left]-height[i];
}else{
left=i;
}
i++;
}else{
if(height[j]<height[right]){
sum+=height[right]-height[j];
}else{
right=j;
}
j--;
}
}
return sum;
}
关键之处盛水的体积只取决于较短的短板。