Problem description
Trapping Rain Water
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!
Problem analysis This topic solution thinking can refer to Leetcode011:container with the most water analysis, leetcode011 is to find the largest area of the surrounding, there are differences, statistics "water" area, or from both sides to the middle scan, time complexity O (n )。 Here to set a water level h, indicating the height of the current circumference, if the subsequent sweep surface to the lower than H, the description can be filled, statistics; if higher than H, update H.
Code
Run Time: 13msclass solution {public:int Trap (vector<int>& height) {int i = 0, j = height.size () -1;int ans = 0;int h = 0;while (j-i >= 0) {if (Height[i] > Height[j]) {if (Height[j] <= h) {ans + = (h-height[j]);} else{h = Height[j];} j--;} else if (Height[i] < height[j]) {if (Height[i] <= h) {ans + = (h-height[i]); i++;} else{h = Height[i];}} Else{if (Height[i] <= h) {if (i! = j) ans + = 2 * (H-height[i]); Elseans + = (H-height[i]);} else{h = Height[i];} i++; j--;}} return ans;};
Leetcode042:trapping Rain Water