Topic:
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!
The title should be well understood, that is, after the given array, how many units of water can be stored. The way most people online is to accumulate the water each column can hold. Like him. It is my practice to accumulate water that is not less than the first one of my own pillars. Define a start, and each time a piece of water is calculated, start jumps to the right pillar of the water to look for new waters. Until the end. It should be O (n). Now there is a problem, if the 4 2 3 example, if according to the idea, 4, there is no greater than or equal to 4 of the number, then start + + words, the answer is finally zero. The solution is, if later did not find the greater than equal to their own pillars, then you will reduce one, then judge, know that they are zero, or to find not less than their own pillars so far.
OJ proves my method is 5 times times faster than others.
classSolution { Public: intTrapintA[],intN) {intsum = 0, start =-1; while(++start < n && a[start] = = 0);//find the first nonzero zero for start while(Start <N) {intNext = start, minus = 0; while(++next < n && A[next] <A[start]) {Minus+=A[next]; } if(next = = N)//there is no greater or equal number after the description, so the A[start] value is reduced by one and then judged until it is found not less than the current number or has been reduced to 0.{A[start]-= 1; if(A[start] > 0)//as long as it is greater than 0, then there is no less than the current number Continue; } Sum+ = (next-start-1) * A[start]-minus; Start=Next; } returnsum; }};
Found OJ if the comments removed, incredibly faster ...
Leetcode question 41st trapping Rain water