算法题:接雨水

之前看的一道算法题,考虑了很久,记录下自己的解题思路
接雨水:大概类似这样的图表,蓝色部分就是可以接到雨水的部分,例:数组为[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)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值