You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
29 lines
618 B
29 lines
618 B
2 years ago
|
package class22;
|
||
|
|
||
|
// 本题测试链接 : https://leetcode.com/problems/trapping-rain-water/
|
||
|
public class Code02_TrappingRainWater {
|
||
|
|
||
|
public static int trap(int[] arr) {
|
||
|
if (arr == null || arr.length < 2) {
|
||
|
return 0;
|
||
|
}
|
||
|
int N = arr.length;
|
||
|
int L = 1;
|
||
|
int leftMax = arr[0];
|
||
|
int R = N - 2;
|
||
|
int rightMax = arr[N - 1];
|
||
|
int water = 0;
|
||
|
while (L <= R) {
|
||
|
if (leftMax <= rightMax) {
|
||
|
water += Math.max(0, leftMax - arr[L]);
|
||
|
leftMax = Math.max(leftMax, arr[L++]);
|
||
|
} else {
|
||
|
water += Math.max(0, rightMax - arr[R]);
|
||
|
rightMax = Math.max(rightMax, arr[R--]);
|
||
|
}
|
||
|
}
|
||
|
return water;
|
||
|
}
|
||
|
|
||
|
}
|