leetcode 42. Trapping Rain Water
来源:互联网 发布:淘宝怎么看买家秀 编辑:程序博客网 时间:2024/06/07 01:26
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!
Subscribe to see which companies asked this question.
这道题看起来挺难解决,其实想通其中的逻辑,还是很简单的。
每个水槽的存水量等于左边最高的长度和右边最高的长度的最小值减去自身的长度。把所有的水槽的值加起来即可。
public class Solution { public int trap(int[] height) { if(height.length<3)return 0; int[]left = new int[height.length]; int[]right = new int[height.length]; left[0] = height[0]; right[height.length-1] = height[height.length-1]; int max = left[0]; for(int i=1;i<height.length;i++){ left[i] = Math.max(height[i],max); max = Math.max(max,height[i]); } max = right[height.length-1]; for(int j=height.length-2;j>=0;j--){ right[j] = Math.max(height[j],max); max = Math.max(height[j],max); } int count = 0; for(int i=1;i<height.length-1;i++){ count += Math.min(left[i],right[i]) - height[i]; } return count; }}
阅读全文
0 0
- [LeetCode]42.Trapping Rain Water
- LeetCode --- 42. Trapping Rain Water
- LeetCode 42.Trapping Rain Water
- [Leetcode] 42. Trapping Rain Water
- [leetcode] 42.Trapping Rain Water
- 【leetcode】42. Trapping Rain Water
- ***LeetCode 42. Trapping Rain Water
- Leetcode 42. Trapping Rain Water
- leetcode 42. Trapping Rain Water
- [LeetCode]42. Trapping Rain Water
- leetcode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- leetcode.42. Trapping Rain Water
- [leetcode] 42. Trapping Rain Water
- LeetCode-42.Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- 如何节省内存空间
- 蓝桥-BASIC-27-2n皇后问题
- react路由提高(Prompt、Redirect、match、Switch)
- xml生成
- 动态顺序表(C语言实现)
- leetcode 42. Trapping Rain Water
- 解决oracle速度变慢
- angular2 Http请求
- [LeetCode] Unique Paths II 起点与终点确定的路径数II
- 插入法 排列 linked list
- Python基础(4)-文件操作
- Gradle版本管理-升级与降级
- hbase安装中遇到的一些问题及解决办法
- LeetCode 10. Regular Expression Matching