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!
This problem is similar to the problem of giving a child sugar, it can be traversed on the left, and the right is traversed again.
Public intTrap (int[] height) { intMax =0; intres =0; intSize =height. Count (); if(Size <=2)returnRes; varMaxarr =New int[size]; for(inti =0;i< height. Count (); i++) {Maxarr[i]=Math.max (Height[i],max); Max=Math.max (Max,height[i]); } intrightmost =0; intLessheight =0; for(inti = size-1; i>=0; i--) {rightmost=Math.max (rightmost, height[i]); Lessheight=math.min (rightmost, maxarr[i]); Res+ = (Lessheight-height[i] >0)? Lessheight-height[i]:0; } returnRes; }
Referring to the practice of the great God on the OJ, stack only has the index of the element that is smaller than the Peek value, because index is used to calculate the width between two edges. This method is to layer the water, that is, such as test case in the middle of the part of the water, because first appeared 1 of the right edge, first with 1 of water, and then encountered 3 of the boundary, left to 1 when no water added, the left is 2 when added water, the height of the water for the lower side with the base difference (Min (
Public intTrap (int[] height) { intres =0; intSize =height. Count (); if(Size <=2)returnRes; inti =0; varstack =Newstack<int> ();//Store the Largerst heigth index while(i<size) { if(Stack. Count () = =0|| Height[i] <= height[stack. Peek ()]) stack. Push (i++); Else { intbot =stack. Pop (); Res+ = (stack. Count () = =0)?0:((Math.min (height[stack. Peek ()], height[i])-Height[bot]) * (I-stack. Peek ()-1));; } } returnRes; }
Trapping Rain Water