https://leetcode.com/articles/trapping-rain-water/
Finish a hard difficulty of the topic, the individual is very excited, suddenly that feel "double pointer" is simply an artifact, the title requirements of the entire container can be filled with the amount of water, intuitively, only the groove part can be filled with water, violent search method is too high complexity, the best way is to use a double pointer, left and right to place one, Notice how much of the water is shorter that side of the decision, if the left height is less than the right, then continue to check whether the left height is greater than or equal to Left_max, if it is updated Left_max, otherwise accumulated water;
The code is as follows
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4 //Self According to the official answer pseudo code complete5 intLen =height.size ();6 intleft =0, right = Len-1;7 //int ans = 0, Left_max = height[left], Right_max = height[right];8 intAns =0, Left_max =0, Right_max =0;//here the Mgax is initialized to 0, otherwise it will go wrong, such as height is empty, the above code will access the subscript-1 element9 while(Left <Right )Ten { One if(Height[left] <Height[right]) A { - if(Height[left] >=Left_max) -Left_max =Height[left]; the Else -Ans + = Left_max-Height[left]; -left++; - } + Else - { + if(Height[right] >=Right_max) ARight_max =Height[right]; at Else -Ans + = Right_max-Height[right]; -right--; - } - } - returnans; in } -};
Time complexity: O (N)
Space complexity: O (1)
two brushes , 2018-03-14, missing update righ with left part
Leetcode 42. Trapping Rain Water