​LeetCode刷题实战42:接雨水

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 接雨水,我们先来看题面:

https://leetcode-cn.com/problems/trapping-rain-water/

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

题意

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

样例

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

解题

暴力解法:

从整个数组的角度看来,如果找到某一索引i左侧的最大值leftMax,以及索引i右侧的最大值rightMax,就可以知道当前索引i的盛水高度为Math.min(leftMax,rightMax)-height[i]。

由于我们需要对每一索引i都寻求其左侧最大值leftMax和右侧最大值rightMax,因此时间复杂度是O(n ^ 2)级别的,其中n为height数组的长度。空间复杂度是O(1)级别的。

public class Solution {
  
  public int trap(int[] height) {
    int n = height.length;
    int result = 0;
    if(n == 0 || n == 1) {
      return result;
    }
    for (int i = 1; i < n - 1; i++) {
      int leftMax = 0;
      for (int j = 0; j < i; j++) {
        leftMax = Math.max(leftMax, height[j]);
      }
      int rightMax = 0;
      for (int j = i + 1; j < n; j++) {
        rightMax = Math.max(rightMax, height[j]);
      }
      int min = Math.min(leftMax, rightMax);
      if(min > height[i]) {
        result += min - height[i];
      }
    }
    return result;
  }
}

本题还有很多解法,你可以尝试想一下,欢迎在评论区留言 。

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。

上期推文:

LeetCode1-20题汇总,速度收藏!

LeetCode21-40题汇总,速度收藏!

LeetCode刷题实战40:组合总和 II

LeetCode刷题实战41:缺失的第一个正数

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小猿666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值