LeetCode || 42. 接雨水

时间: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值