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.
Idea: The amount of water that a certain lattice can hold depends on the lower of the two tallest lattices on either side. Consider traversing from both sides toward the middle, where height represents the current storage watermark, and if A[left]>=height && a[right]>=height, the height is set to Min{a[left],a[right]}, The current storage watermark is raised. Priority to advance the lower side of the storage waterline.
1 classSolution {2 Public:3 intTrapintA[],intN) {4 if(N <=2) {return 0; }5 intContent =0;6 intleft =0, right = N1, height =0;7 while(Left <=Right ) {8 if(A[left] < height) {content + = Height-a[left]; ++left;Continue; }9 if(A[right] < height) {content + = Height-a[right];--right;Continue; }Ten if(A[left] <=A[right]) { OneHeight =A[left]; A++Left ; -}Else { -Height =A[right]; the--Right ; - } - } - returncontent; + } -};
Trapping Rain Water