首页 > 代码库 > [leetcode]Trapping Rain Water

[leetcode]Trapping Rain Water

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! 

算法思路:

短板效应,蓄水量与桶的短板相关。求出height数组中的最长板,然后从两端向长板迭代,遇到更短的则求出蓄水量,遇到较长的,则更新边缘。

代码如下:

 1 public class Solution { 2     public int trap(int[] height) { 3         if(height == null || height.length < 3) return 0; 4         int max = 0; 5         for(int i = 0; i < height.length;i++){ 6             if(height[i] > height[max]) max = i; 7         } 8         int high = 0,res = 0; 9         for(int i = 0; i < max; i++){10             if(height[i] < height[high]){11                 res += height[high] - height[i];12             }else if(height[i] > height[high]){13                 high = i;14             }15         }16         high = height.length - 1;17         for(int i = height.length - 1; i > max; i--){18             if(height[i] < height[high]){19                 res += height[high] - height[i];20             }else if(height[i] > height[high]){21                 high = i;22             }23         }24         return res;25     }26 }

具体算法分析可以参考这里。