题意:
给一个 由多个矩形组成的容器,问能最多接多少雨水,
思路:
对于每个矩形,他能接的雨水的数量,取决于左右最高矩形,如果当前矩形的高度比左右最大高度分别都小,那么必能接到水。
java代码1:///比较好理解,开两个数组,分别表示当前位置左右矩形的最大高度。
class Solution {
public int trap(int[] height) {
int len = height.length;
if(len<=2){
return 0;
}
int[] left = new int[len];
int[] right = new int[len];
int maxx = height[0];
for(int i = 1;i<len-1;i++){
left[i] = maxx;
maxx = Math.max(maxx,height[i]);
}
maxx = height[len-1];
for(int i = len-1;i>0;i--){
right[i] = maxx;
maxx = Math.max(maxx,height[i]);
}
int ans = 0;
for(int i = 1;i<len-1;i++){
if(height[i]<left[i]&&height[i]<right[i]){
ans += Math.min(left[i],right[i])-height[i];
}
}
return ans;
}
}
java代码2:///利用双指针,空间和时间都降低了
class Solution {
public int trap(int[] height) {
int len = height.length;
if(len<=2){
return 0;
}
int l = 1;
int r = len-2;
int lmax = height[0];
int rmax = height[len-1];
int ans = 0;
while(l<=r){
if(lmax<rmax){
if(height[l]<lmax){
ans += lmax-height[l];
}
else{
lmax = height[l];
}
l++;
}
else{
if(height[r]<rmax){
ans += rmax-height[r];
}
else{
rmax = height[r];
}
r--;
}
}
return ans;
}
}