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.
解题:
第一次尝试,一层一层找,虽然算法没错 但是time out了
网上资料:
找到制高点,然后分别从两端往中间遍历。
遍历的过程中记录局部的最高点,当前高度与局部最高点之间的差值就是当前位置的水量。
代码如下:
public int trap(int []height){
if(height.length<=2)
return 0;
//get max height
int max_height = height[0];
int max_index = 0;
for(int i=0;i<height.length;i++){
if(max_height<=height[i]){
max_height = height[i];
max_index=i;
}
}
int result=0;
int jubu_max_l=height[0];
for(int i=1;i<max_index;i++){
if(height[i]>=jubu_max_l)
jubu_max_l = height[i];
else
result += (jubu_max_l-height[i]);
}
int jubu_max_r =height[height.length-1];
for(int i=height.length-2;i>max_index;i--){
if(height[i]>=jubu_max_r)
jubu_max_r=height[i];
else
result += (jubu_max_r-height[i]);
}
return result;
}