首页 > 代码库 > 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
.
参考:
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 }//for12 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 }//for18 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 }//for25 26 return waterSum;27 }28 29 }
Trapping Rain Water
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。