LeetCode 42 Trapping Rain Water
来源:互联网 发布:演示文稿制作软件 编辑:程序博客网 时间:2024/04/30 02:24
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
.
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
解题思路:从这个网址上学到一个思想,http://blog.unieagle.net/2012/10/31/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Atrapping-rain-water/
决定一个水槽的容积为两个左右的高度,并取决于两者的最小高度。对于数组每个元素来讲,我们可以求出两个这样的高度,最后相加其最小。那么,我们考虑只考虑一个单边,以左边为例,从左边开始遍历其相对于已有的最高高度的高度差即为单边的高度。右边亦然,两者最小求和,即为总的容积。
从左边开始遍历,记录相对于已有的最高值的差值。同时,从右边开始遍历记录相对于右边已有的最高值的差值。
public int trap(int[] height) { int len = height.length; if(len<=2)return 0; int [] test = new int[len+1]; int max = 0; int sum = 0; for (int i = 0; i < len; i++) { test[i]=max-height[i]>0?max-height[i]:0; if(height[i]>max){ max = height[i]; } } max = 0; int temp =0; for (int i = len-1; i > 0; i--) { temp = max-height[i]>0?max-height[i]:0; sum += temp>test[i]?test[i]:temp; if(height[i]>max){ max = height[i]; } } return sum; }
- [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
- leetcode -- Copy List with Random Pointer -- deep copy问题,dfs
- merge include viewstub
- 第十周 项目二 二叉树遍历的递归算法
- C语言 malloc
- Android中Activity.this,getApplicationContext(),getBaseContext()和this详解
- LeetCode 42 Trapping Rain Water
- 第十二周项目4-(5)应用图的深度优先遍历思路求解问题
- 45种攻入网站后台的方法【安全防护策略】
- java aio
- 常见错误小结
- maven基本命令,配置和扩展
- Android测试
- 【Android】瀑布流
- Oralce数据库的优化(面试必问题)