Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the 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 the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!
Puzzle: In the online study for half a day, only to find the time O (n) and Space O (1) algorithm:
- First find the largest bar, the index is recorded in the Totalmaxindex variable;
- From left to right, and then to the bar on the left of Totalmaxindex, set a Curmax record to traverse to the largest bar so far, for A[i], there are two possibilities: one is A[i]<curmax, then you can store water (Curmax-a[i]) But A[i] > curmax, then update curmax = A[i];
- From right to left, the bar to the right of the totalmaxindex, in turn, method with 2.
The specific algorithm process is as follows:
The basic principle is that when traversing from left to right, the highest bar ensures that the water can be stopped at the right end, so long as the calculation for A[i], the left side can intercept how high the water can be, that is, variable Curmax.
The code is as follows:
1 Public classSolution {2 Public intTrapint[] A) {3 if(A = =NULL|| A.length = = 0)4 return0;5 6 intCurmax = 0;7 intTotalmax = a[0];8 intTotalmaxindex = 0;9 intAnswer = 0;Ten One for(inti = 1;i < a.length;i++){ A if(A[i] >Totalmax) { -Totalmax =A[i]; -Totalmaxindex =i; the } - } - - for(inti = 0;i < totalmaxindex;i++){ + if(A[i] <Curmax) -Answer + = Curmax-A[i]; + Else ACurmax =A[i]; at } - -Curmax = 0; - for(inti = a.length-1;i > totalmaxindex;i--){ - if(A[i] <Curmax) -Answer + = Curmax-A[i]; in Else { -Curmax =A[i]; to } + } - the returnanswer; * } $}