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!
Ideas:
This problem is similar to the Leetcode 11 question container with the most water. The maximum amount of water is required. There are two ways to do it.
Idea One:
First, walk from left to right. Each traversal of a number, greedy to get the number of the lattice can be filled with water. Since it is a left-to-right traversal, we only consider the height of the left, without considering the height of the right (the one that should actually be smaller). So we need to walk from right to left, and the same greedy number lattice
The maximum amount of water can be loaded, this time to the right height to prevail. Finally, combine left-to-right and right-to-left results, whichever is smaller.
Code: (Runtime 19ms)
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4vector<int>LeftToRight;5vector<int>RightToLeft;6 aux_function (Height.begin (), Height.end (), lefttoright);7 8 aux_function (Height.rbegin (), Height.rend (), rightToLeft);9 Ten intAns =0; OneAuto It1 =Lefttoright.begin (); AAuto It2 =Righttoleft.rbegin (); - - while(It1! =Lefttoright.end ()) { theAns + = min (*it1++, *it2++); - } - returnans; - } + - Private: +template<classIter> A voidAux_function (ITER begin, ITER end, vector<int> &ret) { at intleft =0; - for(Auto it = begin; it! = end; it++) { -left = left > *it? Left: *it; -Ret.push_back (Left-*it); - } - } in};View Code
Idea two:
As shown in, the total area of the black lattice and the blue lattice is first obtained, and then the respective area of black is subtracted.
Code: (Runtime 10ms)
classSolution { Public: intTrap (vector<int>A) {intn =a.size (); intSummap =0; intSumtot =0; for(inti =0; I < n; i++) Summap + =A[i]; intleft =0, right = N-1; intLeftbar =0, Rightbar =0; while(Left <=Right ) {Leftbar=Max (A[left], leftbar); Rightbar=Max (A[right], rightbar); if(Leftbar <=Rightbar) {Sumtot+=Leftbar; Left++; //right--;}Else{Sumtot+=Rightbar; Right--; //left++; } } returnSumtot-Summap; }};View Code
Leetcode problem-trapping Rain water