LeetCode: Trapping Rain Water 解题报告
2014-10-28 17:27
453 查看
https://oj.leetcode.com/problems/trapping-rain-water/
[b]Trapping Rain Water[/b]
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!
SOLUTION 1:
从左到右扫描,计算到从左边到curr的最高的bar,从右到左扫描,计算到从右边到curr的最高的bar。
再扫描一次,把这两者的低者作为{桶}的高度,如果这个桶高于A[i]的bar,那么A[i]这个bar上头可以存储height - A[i]这么多水。把这所有的水加起来即可。
View Code
CODE:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/Trap.java
[b]Trapping Rain Water[/b]
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!
SOLUTION 1:
从左到右扫描,计算到从左边到curr的最高的bar,从右到左扫描,计算到从右边到curr的最高的bar。
再扫描一次,把这两者的低者作为{桶}的高度,如果这个桶高于A[i]的bar,那么A[i]这个bar上头可以存储height - A[i]这么多水。把这所有的水加起来即可。
public class Solution { public int trap(int[] A) { // 2:37 if (A == null) { return 0; } int len = A.length; int[] l = new int[len]; int[] r = new int[len]; for (int i = 0; i < len; i++) { if (i == 0) { l[i] = A[i]; } else { l[i] = Math.max(l[i - 1], A[i]); } } int water = 0; for (int i = len - 1; i >= 0; i--) { if (i == len - 1) { r[i] = A[i]; } else { // but: use Math, not max r[i] = Math.max(r[i + 1], A[i]); } water += Math.min(l[i], r[i]) - A[i]; } return water; } }
View Code
CODE:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/Trap.java
相关文章推荐
- [LeetCode] Trapping Rain Water 解题报告
- [leetcode] 407. Trapping Rain Water II 解题报告
- Leetcode 407. Trapping Rain Water II 收集雨水2 解题报告
- [Leetcode] 407. Trapping Rain Water II 解题报告
- [LeetCode] Trapping Rain Water 解题报告
- [LeetCode]Trapping Rain Water,解题报告
- 【LeetCode】Trapping Rain Water解题报告
- 【LeetCode】42.Trapping Rain Water(Hard)解题报告
- LeetCode 42: Trapping Rain Water 解题与思考
- [leetcode] 42. Trapping Rain Water 解题报告
- [Leetcode] 42. Trapping Rain Water 解题报告
- leetcode -- Trapping Rain Water -- 重点
- LeetCode (Trapping Rain Water)
- [LeetCode] Trapping Rain Water 栈
- [C++]LeetCode: 131 Trapping Rain Water (双边扫描)
- Leetcode42 Trapping Rain Water
- LeetCode 407. Trapping Rain Water II
- [leetcode]407. Trapping Rain Water II
- leetcode: Trapping Rain Water
- LeetCode - Trapping Rain Water