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
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
双指针,需要把情况考虑全。
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
|
class
Solution {
public :
int
trap( int
A[], int
n) {
int
result = 0;
int
l = 0,r = n-1;
while (A[l]==0)l++;
while (A[r]==0)r--;
int
h = 0;
h = min(A[l],A[r]);
while (l < r)
{
if (A[l] <= h)
{
result += h - A[l];
l++;
}
else
if (A[r] < h)
{
result += h - A[r];
r--;
}
else
if (A[l] > h && A[r] == h)
{
r--;
}
else
if (A[r] > h && A[l] == h)
{
l++;
}
else
if (A[l]>h &&A[r]>h)
{
h = min(A[l],A[r]);
}
}
return
result;
}
}; |