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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1],
return 6.
public class Solution {
public int trap(int[] A) {
if (A == null || A.length <= 2) return 0;
int maxIndex = 0;
for (int i = 1; i < A.length; i++) {
if (A[i] > A[maxIndex]) {
maxIndex = i;
}
}
int leftMax = A[0];
int total = 0;
for (int i = 1; i < maxIndex; i++) {
if (A[i] < leftMax) {
total += (leftMax - A[i]);
} else {
leftMax = A[i];
}
}
int rightMax = A[A.length - 1];
for (int i = A.length - 2; i > maxIndex; i--) {
if (A[i] < rightMax) {
total += (rightMax - A[i]);
} else {
rightMax = A[i];
}
}
return total;
}
}
本文介绍了一个算法,用于计算给定高度数组表示的雨后能存留的雨水量。通过遍历数组并计算每个柱子两侧最高柱子的最小值,可以得出每个位置能存留的雨水量,最终累加得到总存留水量。
390

被折叠的 条评论
为什么被折叠?



