算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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;
}
}
本题还有很多解法,你可以尝试想一下,欢迎在评论区留言 。
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。
上期推文: