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!
Idea: Find the maximum value and its position pos. The POS is then traversed from left to right, and then to the POS from right to left.
When do you add water?
When traversing the maximum value, that is, the second largest value of the global, if the current value is smaller than the second largest, then the water will be added, the small amount of how much.
The addition of water is a list of columns added.
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4 if(Height.size () <=2)return 0;5 intresult=0;6 intpos=0, maxheight=0;7 for(intI=0; I)8 {9 if(height[i]>maxheight)Ten { OneMaxHeight =Height[i]; Apos =i; - } - } the intCur_max = height[0]; - for(intI=1; i<pos;i++) - { -Cur_max =Max (cur_max,height[i]); +result+= (cur_max-height[i]); - } +Cur_max = Height[height.size ()-1]; A for(intI=height.size ()-2; i>pos;i--) at { -Cur_max =Max (cur_max,height[i]); -result+= (cur_max-height[i]); - } - returnresult; - } in};
In fact, you do not need to find the maximum value. Follow the idea of finding the maximum value. Move the second largest value. The idea is the same as above. The code is simple.
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4 if(Height.size () <=2)return 0;5 intresult=0;6 intleft=0, Right=height.size ()-1, secheight=0;7 while(left<Right )8 {9 if(height[left]<Height[right])Ten { OneSecheight =Max (height[left],secheight); Aresult+= (secheight-Height[left]); -left++; - } the Else - { -Secheight =Max (height[right],secheight); -result+= (secheight-height[right]); +right--; - } + } A returnresult; at } -};
[Leetcode] Trapping Rain Water