42. 接雨水
作者:互联网
题目链接:https://leetcode-cn.com/problems/trapping-rain-water/
点击查看代码
public class Solution {
// leetcode42,接雨水
public int trap(int[] height) {
int size = height.length;
if (size <= 1) {
return 0;
}
int[] lh = new int[size];
int[] rh = new int[size];
lh[0] = 0;
for (int i = 1; i < size; i++) {
lh[i] = Math.max(lh[i - 1], height[i-1]);
}
rh[size - 1] = 0;
for (int i = size - 2; i >= 0; i--) {
rh[i] = Math.max(rh[i + 1], height[i+1]);
}
int sum = 0;
for (int i = 1; i <= size - 2; i++) {
// 第i列可装雨水量为左边或右边最高度-当前列的高度:max(0, min(lh, rh) - curh)
sum += Math.max(Math.min(lh[i], rh[i]) - height[i], 0);
}
return sum;
}
}
标签:int,42,雨水,height,rh,public,size 来源: https://www.cnblogs.com/aizi/p/16106882.html