0
点赞
收藏
分享

微信扫一扫

42. Trapping Rain Water


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.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-37ZzDROn-1571543148239)(http://www.leetcode.com/wp-content/uploads/2012/08/rainwatertrap.png)]

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!

思路:
从两边往中间搜索

class Solution {
public int trap(int[] height) {
int secHight = 0;
int left = 0;
int right = height.length-1;
int area = 0;
while (left < right){
if (height[left] <height[right]){
secHight = Math.max(height[left], secHight);
area += secHight-height[left];//计算当前格的能装雨水的容量
left++;
} else {
secHight = Math.max(height[right], secHight);
area += secHight-height[right];
right--;
}
}
return area;
}
}

class Solution {
public int trap(int[] height) {
int answer = 0;

if(height.length > 2) {
int[] maxLeft = new int[height.length],
maxRight = new int[height.length];
maxLeft[0] = 0;
maxRight[maxRight.length - 1] = 0;

for (int left = 1; left < height.length; left++) {
int right = height.length - 1 - left;
maxLeft[left] = Math.max(maxLeft[left - 1], height[left - 1]);
maxRight[right] = Math.max(maxRight[right + 1], height[right + 1]);
}

for(int i = 0; i < height.length; i++) {
int difference = Math.min(maxLeft[i], maxRight[i]) - height[i];
answer += difference > 0 ? difference : 0;
}
}

return answer;
}
}


举报

相关推荐

0 条评论