码迷,mamicode.com
首页 > 移动开发 > 详细

Trapping Rain Water

时间:2015-01-27 14:45:03      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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.

技术分享

参考:

http://blog.csdn.net/doc_sgl/article/details/12307171

 1 public class Solution {
 2     public int trap(int[] A) {
 3         int waterSum = 0;
 4         int leftMaxHeight[] = new int[A.length];
 5         int rightMaxHeight[] = new int[A.length];
 6         
 7         int maxHeight = 0;
 8         for(int i = 0; i < A.length; i++){
 9             leftMaxHeight[i] = maxHeight;
10             maxHeight = maxHeight > A[i] ? maxHeight : A[i];
11         }//for
12         
13         maxHeight = 0;
14         for(int i = A.length - 1; i >= 0; i--){
15             rightMaxHeight[i] = maxHeight;
16             maxHeight = maxHeight > A[i] ? maxHeight : A[i];
17         }//for
18         
19         for(int i = 0; i < A.length; i++){
20             int minHeight = Math.min(leftMaxHeight[i], rightMaxHeight[i]);
21             int elementSum = minHeight - A[i];
22             if(elementSum > 0)
23                 waterSum += elementSum;
24         }//for
25         
26         return waterSum;
27     }
28     
29 }

 

Trapping Rain Water

标签:

原文地址:http://www.cnblogs.com/luckygxf/p/4252766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!