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 Solving Ideas:
1, my method: The thought of the two sides of the clip, if the left side is less than the right, then move the left hand, otherwise move the pointer to the right. At the same time, if the moving pointer is less than the previous minimum height, the capacity minus the height that the move pointer refers to at this point. If both the moving pointer and the non-moving pointer are greater than the previous minimum height, the excess is added. Don't understand, the code is better understood:
Class Solution {Public:int trap (vector<int>& height) {int len = height.size (), if (len<3) {return 0;} int start = 0, end = Len-1;int result = 0, MinH = 0;minh = Min (Height[start], height[end]); result = MinH * (end-start -1); while (start<end-1) {if (Height[start]2, online Another good way is left and right side sweep method. Record the maximum number of left and right of each number. The left largest and the right largest constitute a container, which subtracts itself from the space, which corresponds to the steps of this position contributed capacity.Class Solution {Public:int trap (vector<int>& height) {int len = height.size (), if (len<3) {return 0;} int Maxl[len], maxr[len];int maxh = height[0];maxl[0] = 0;for (int i=1; i<len; i++) { maxl[i] = maxh; MAXH = Max (Maxh, Height[i]);} Maxh = height[len-1];maxr[len-1]=0;int result=0;for (int i=len-2; i>=0; i--) { maxr[i]=maxh; MAXH = Max (Maxh, Height[i]); Result +=max (0, Min (maxl[i], maxr[i])-height[i]);} return result;};
[Leetcode] Trapping Rain Water