Solution: (1) Set up a two-dimensional array, record the left highest point of each position and the right highest point, can be calculated by O (n).
(2) According to the above information and the current height, calculate the vertical direction of the point can hold how much water, still O (n) completed.
In the synthesis, the asymptotic time complexity is O (n);
Class Solution {
Public
int trap (int a[], int n) {
if (n<=0)
return 0;
int* High=new int[n*2];
high[0*2+0]=0;
for (int i=1;i<n;i++) {
if (a[i-1]>high[(i-1) *2+0])
HIGH[I*2+0]=A[I-1];
Else
high[i*2+0]=high[(i-1) *2+0];
}
high[(n-1) *2+1]=0;
for (int i=n-2;i>=0;i--) {
if (a[i+1]>high[(i+1) *2+1])
HIGH[I*2+1]=A[I+1];
Else
high[i*2+1]=high[(i+1) *2+1];
}
int sum=0;
for (int i=0;i<n;i++) {
int tmp=high[i*2+0]>high[i*2+1]?high[i*2+1]:high[i*2+0];
Tmp=tmp-a[i];
if (tmp<0)
Tmp=0;
sum+=tmp;
}
Delete[] High;
return sum;
}
};
Leetcode-trapping Rain Water Solution