首页 > 移动平台 > 详细

[leetcode]Trapping Rain Water

时间:2014-08-08 12:30:45      阅读:326      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣

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 }

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

 

[leetcode]Trapping Rain Water,布布扣,bubuko.com

[leetcode]Trapping Rain Water

原文:http://www.cnblogs.com/huntfor/p/3898901.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!