之前看的一道算法题,考虑了很久,记录下自己的解题思路
接雨水:大概类似这样的图表,蓝色部分就是可以接到雨水的部分,例:数组为[0,2,0,4,0,2,0,4,0],可接雨水量则为6,只要有凹陷处就能接到雨水,要求输入数组,输出可接的雨水量
我的思路是这样的:
把图表填充,以数组中的最大值作为矩形的一条边,以数组的长度作为矩形发另一条边,这样求得整个面积A,
黑色部分面积可以根据数组算得B,那现在的目标只要求出黄色部分面积就可以了,黄色部分的面积有一个特点,就是它不会出现两边凹陷中间凸出的情形。
1、根据数组,求得整个数组所占面积
2、算出数组中的最大值以及对应的index,随即算出整体面积
3、截取数组在最大index之前的数,倒序寻找最大值以及对应位置,此时找到的最大值和第2歩找到的最大值之间会形成黄色部分的面积,递归后就能算出在最大index左边黄色部分的面积
4、倒序原数组,重复2、3歩,得出最大index右边黄色部分的面积
5、用总面积减去数组的整体面积减去黄色部分面积,即可得出蓝色部分雨水的面积
贴上代码:
// 黄色空白部分面积
var sq = 0;
var isneedstop = false;
function start (height) {
var max = this.culMax(height).max;
var maxIndex = this.culMax(height).maxIndex
// 总面积
var square = max * height.length;
// 数组总面积
var total = 0
height.map(el => {
total += el
});
this.culBeforeArr(height, max, maxIndex);
this.culAfterArr(height);
var result = square - total - sq;
return result
};
function culMax(height) {
var max = 0;
var maxIndex = 0;
for (let i in height) {
if (height[i] >= max) {
max = height[i]
maxIndex = i
}
}
return { max, maxIndex }
};
function culBeforeArr(height, max, maxIndex) {
var beforeArr = height.slice(0, maxIndex);
var beforeMax = 0;
var beforeMaxIndex = 0;
for (let a = maxIndex - 1; a >= 0 && a < beforeArr.length; a--) {
if (beforeArr[a] >= beforeMax) {
beforeMax = beforeArr[a]
beforeMaxIndex = a
}
}
sq += (maxIndex - beforeMaxIndex) * (max - beforeMax);
if (beforeMaxIndex) {
this.culBeforeArr(height, max, beforeMaxIndex)
}
if (isneedstop) {
return
}
if (beforeMaxIndex == 0) {
isneedstop = true
this.culBeforeArr(height, max, beforeMaxIndex)
}
}
function culAfterArr(height) {
var re_height = height.reverse();
var re_max = this.culMax(re_height).max;
var re_maxIndex = this.culMax(re_height).maxIndex;
this.culBeforeArr(re_height, re_max, re_maxIndex)
}