时间:2019.4.29 周一
题目:给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
解法一:
(1)遍历找到最大元素(最高元素)
(2)求以这个最大元素为高,以数组长度为宽的长方形面积。此长方形面积 = 接水面积 + 柱体面积 + 空白面积
(3)分别从两边往最高点遍历。
class Solution {
public int trap(int[] height) {
if(height.length < 2) return 0;
int max = 0;
int totalArea = 0;
// 1.找出数组最大元素,同时减去柱体面积
for(int i = 0; i < height.length; i++) {
totalArea -= height[i];
if(max < height[i])
max = height[i];
}
// 2.加上长方形面积
totalArea += max * height.length;
int tempMax = 0;
int j = 0;
for(; height[j] < max; j++) {
if(height[j] > tempMax) {
totalArea -= (height[j] - tempMax) * j;
tempMax = height[j];
}
}
totalArea -= (height[j] - tempMax) * j;
tempMax = height[height.length - 1];
int k = height.length - 1;
for(; height[k] < max; k--) {
if(height[k] > tempMax) {
totalArea -= (height[k] - tempMax) * (height.length - 1 - k);
tempMax = height[k];
}
}
totalArea -= (height[k] - tempMax) * (height.length - 1 - k);
return totalArea;
}
}
结果分析:
时间复杂度:O(n)
空间复杂度:O(n),使用恒定的额外空间
其它解法: https://leetcode.windliang.cc/leetCode-42-Trapping-Rain-Water.html