分析1:1)一一找比当前的大的值,这样就有了当前到下一个大的值之间可以存储水;
2)当找到了下一个大的值,以此为起点继续1)
使用1),2)从左向右记录值;从右向左记录值。 返回总和。
public class Solution {
public int trap(int[] A) {
int result=0;
int[] left_collect = new int[A.length];
int[] right_collect = new int[A.length];
for(int i=1; i<A.length;i++)
{
left_collect[i]=Math.max(A[i-1],left_collect[i-1]);
right_collect[A.length-i-1]=Math.max(A[A.length-i],right_collect[A.length-i]);
}
for(int i=0; i<A.length; i++)
{
int height = Math.min(left_collect[i],right_collect[i]);
if(height > A[i])
result += (height-A[i]);
}
return result;
}
}
分析2:1)找到最高的点为起点,向两边找到第二高的点
2)以第二高的点为起点,继续1)同时记录存储水量
public class Solution {
public int trap(int[] A) {
int result=0;
int max = 0;
for(int i=1; i<A.length; i++)
{
if(A[i]>A[max])
max=i;
}
for(int i=0, peak=0; i<max; i++){
if(A[i]>A[peak])
peak=i;
else
result += (A[peak]-A[i]);
}
for(int j=A.length-1, peak=A.length-1; j>max ;j--){
if(A[j]>A[peak])
peak=j;
else
result += (A[peak]-A[j]);
}
return result;
}
}
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
.