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.
题意
样例
输出: 6
解题
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;
}
}
上期推文: