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: Use two pointers left and right, respectively, from both ends to the middle. Also, record the highest value that left and right have ever been to. If the current value does not exceed the maximum value, the highest value is the amount of water as the current difference, and the pointer is one (the right pointer is minus one). In order for this method to work (the invalid case is that the bar that the pointer subsequently meets will no longer be above the maximum value, then the water does not exist at all), so we only move the shorter one at the left and right (if the two are equal, move left). In this way, it is guaranteed to end up with a bar (at least equal height) higher than the highest value, because we are moving the short pointer and moving forward will definitely end up with another high pointer.
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4 if(height.size () = =0)return 0;5 intleft =0, right = Height.size ()-1, res =0;6 intMaxleft = Height[left], maxright =Height[right];7 while(Left <Right )8 {9 if(Height[left] <=Height[right])Ten { One if(Height[left] > maxleft) maxleft =Height[left]; A ElseRes + = Maxleft-Height[left]; -left++; - } the Else - { - if(Height[right] > maxright) maxright =Height[right]; - ElseRes + = Maxright-Height[right]; +right--; - } + } A returnRes; at } -};
Bar height Question: This is an issue in Amazon's interview. The highest level of liquid surface. You just need to change the code above to use it. is when the Res value changes, if Max and the current height difference value is nonzero, the max value is recorded, and the last highest max value is the result.
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4 if(height.size () = =0)return 0;5 intleft =0, right = Height.size ()-1, res =0;6 intMaxleft = Height[left], maxright =Height[right];7 while(Left <Right )8 {9 if(Height[left] <=Height[right])Ten { One if(Height[left] > maxleft) maxleft =Height[left]; A Else if(Maxleft-height[left] >0) -res =Max (res, maxleft); -left++; the } - Else - { - if(Height[right] > maxright) maxright =Height[right]; + Else if(Maxright-height[right] >0) -res =Max (res, maxright); +right--; A } at } - returnRes; - } -};
Trapping Rain Water (Bar Height)--Leetcode