Problem description
Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how Much water it is 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!
Solution Ideas
assuming that the length of the array is Len, (1) Find the tallest pillar highest;
(2) Double hands: from 0 to highest, from len-1 to highest;
(3) Auxiliary stack s: The column height of the ascending sequence, if encountered than the top of the stack of the height of the element, it is able to store water s.peek ()-cur
The complexity of time space is O (n).
Program
public class Solution {public int trap (int[] height) {if (height = = NULL | | height.length = = 0) {return 0;} int highest = GETHIGHESTIDX (height); int water = 0; stack<integer> s = new stack<integer> (); for (int i = 0; i < highest; i++) {if (S.isempty () | | height[i] ; S.peek ()) {S.push (height[i]);} else {water + = S.peek ()-height[i];}} s = new stack<integer> (); for (int i = height.length-1; i > highest; i--) {if (S.isempty () | | height[i] > S.P Eek ()) {S.push (height[i]);} else {water + = S.peek ()-height[i];}} return water;} private int Gethighestidx (int[] height) {int high = 0;int idx = 0;for (int i = 0; i < height.length; i++) {if (height[i ] > High) {high = Height[i];idx = i;}} return idx;}}
Trapping Rain Water