您的位置:首页 > 移动开发

Leetcode-Trapping Rain Water

2014-11-15 06:56 316 查看
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!

Analysis:

We scan the whole array twice. First: from head to end; Second: from end to start.

In every scan, we record the current bar for rain trapping. If the value of current column is less than the bar, then current store += bar-currentValueOfColumn; Else, current store is end, we then add the current store into the total store, and reset the bar as currentValueOfColumn.

Solution:

public class Solution {
public int trap(int[] A) {
if (A.length==0) return 0;
if (A.length==1) return 0;
int index = 1;
int bar = A[0];
int total = 0;
int curStore = 0;
boolean[] count = new boolean[A.length];

//We need to record which column has been counted during the first scan.
for (int i=0;i<count.length;i++) count[i] = false;
List<Integer> countList = new ArrayList<Integer>();

while (index<A.length){
int curBar = A[index];
if (curBar<bar){
curStore+= (bar-curBar);
countList.add(index);
} else {
total += curStore;
curStore = 0;
bar = curBar;
for (int i=0;i<countList.size();i++) count[countList.get(i)]=true;
countList.clear();
}
index++;
}

bar = A[A.length-1];
index = A.length-2;
curStore = 0;
while (index>=0){
int curBar = A[index];
if (curBar<bar && !count[index])
curStore+= (bar-curBar);
else if (curBar>bar){
total += curStore;
curStore = 0;
bar = curBar;
}
index--;
}

return total;
}
}


NOTE: We need to record which column has been counted in the first scan, we then ignor these column in the second scan.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: