题解 | #接雨水问题#
接雨水问题
http://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
写法上没有太多技巧,先从左向右找,找到一个比当前柱子高的,那么这就形成了一个坑,然后计算坑中的水。
再从右向左好,找到一个比当前柱子高的,计算坑中的水。
import java.util.*;
public class Solution {
/**
* max water
* @param arr int整型一维数组 the array
* @return long长整型
*/
public long maxWater (int[] arr) {
// write code here
if (arr.length < 3) {
return 0L;
}
int p1 = 0, p2 = 0;
long result = 0L;
for (; p2 < arr.length; p2++) {
if (arr[p2] >= arr[p1]) {
int t = arr[p1];
for (; p1 < p2; p1++) {
result += (t - arr[p1]);
}
}
}
p1 = arr.length - 1;
p2 = arr.length - 1;
for (; p2 >= 0; p2--) {
if (arr[p2] > arr[p1]) {
int t = arr[p1];
for (; p1 > p2; p1--) {
result += (t - arr[p1]);
}
}
}
return result;
}
}