p42

LeetCode p42 Trapping Rain Water 题解

1.题目:

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.

题意:

给你一个数组,是每个坐标上砖块的高度,为这组砖块最多可以盛多少水。

2.解题思路:

两个指针,分别从左右出发,原理类似于俄罗斯方块,慢慢消掉被堆满的底层~
具体见代码。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 
public class Solution {
public int trap(int[] height) {
if (height.length < 3)
return 0;
int l = 0;
int r = height.length - 1;
int ans = 0;
int last = 0;
while (l < r) {
int min = Math.min(height[l], height[r]);
for (int i = l + 1; i < r; i++) {
if (min == last)
break;
if (height[i] < min) {
if (height[i] < last) {
ans += min - last;
} else {
ans += min - height[i];
}

}
}

last = min;
if (min == height[l]) {
do {
l++;

} while (l < r && height[l] <= min);
} else {
do {
r--;

} while (l < r && height[r] <= min);
}
}

return ans;
}
}

4.一些总结: