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. Thanks Marcos for contributing this image!
头一回一次写对代码,记录一下
想写思路,但实在难以表达,总之需要前后两个指针
public int trap(int[] height) {
int l = 0;
int r = 0;
int min = 0;
int left = 0;
int water = 0;
int right = height.length - 1;
while (left < right) {
//获取当前两端的值
int ln = height[left];
int rn = height[right];
//如果以后后小于之前的高度
if (ln < l) {
if( ln < min) {
water += min - ln;
left++;
continue;
}
}else {
l =ln;
}
if (rn < r) {
if(rn < min) {
water += min - rn;
right--;
continue;
}
} else {
r = rn;
}
//左右两端比较小的
min = Math.min(l, r);
if (height[left] <= height[right]) {
left++;
} else {
right -- ;
}
}
return water;
}