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!
Given n non-negative integers to represent the histogram, the width of each bar is 1, and when it rains, it can fill up to the maximum amount of water.
For example: Given an integer sequence [0,1,0,2,1,0,1,3,2,1,2,1], you should return 6. The blue area shows the water that can be loaded, and the area of the water is 6.
So that array a represents the height sequence, and the length of a is n, then you can find the largest position m in a, and then classify the graph in two parts, that is, the left and right sides, and the processing methods are similar. On the left, you can traverse to m from 0 and record the maximum height. If the current height is greater than or equal to the maximum height, then the location can not be filled with water, it can only be used as the edge of the container, and update the maximum height; Each traversal adds the water that the current position can fit into the sum, and finally gets the water that can be loaded on the left, and the right side can do similar processing. Each element is traversed up to two times, so the time complexity is O (N) and the code is as follows:
intTrap (vector<int>&height) { if(Height.empty ())return 0; intMID =0, mx = height[0]; for(intI=1; Ii) {if(height[i]>mx) {mx=Height[i]; Mid=i; } } intRET =0; intLH =0; for(intI=0; i<mid; ++i) {if(height[i]>LH) LH=Height[i]; Elseret+ = lh-Height[i]; } intRH =0; for(intI=height.size ()-1; i>mid; --i) {if(height[i]>RH) RH=Height[i]; Elseret+ = rh-Height[i]; } returnret;}
Trapping Rain Water