42. Trapping Rain Water

网友投稿 640 2022-11-11

42. Trapping Rain Water

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)(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] 计算当前格的能装雨水的容量 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; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:JSTL核心标签库
下一篇:733. Flood Fill
相关文章

 发表评论

暂时没有评论,来抢沙发吧~