Note:the following idea was in fact from the last answer in this link, which leads to a clean code. I just reorganize it and add some explanations. I hope it is Ok.
The following is four solutions in C/c++/java/python respectively. The basic idea is, we set the pointers and to the left and right l r end of height . Then we get the minimum height ( minHeight ) of these pointers (similar to Container with most water due to the leaking Bucket E Ffect) Since the level of the water cannot is higher than it. Then we move the pointers towards the center. If The coming level was less than minHeight and then it would hold some water. Fill the water until we meet some "barrier" (with height larger than minHeight ) and update and to l repeat this r proc ESS in a new interval.
C
1 intTrapint* Height,intheightsize) {2 intL =0, R = heightsize-1, water =0, MinHeight =0;3 while(L <r) {4 while(L < R && Height[l] <=minheight)5Water + = minheight-height[l++];6 while(R > L && height[r] <=minheight)7Water + = minheight-height[r--];8MinHeight = Height[l] <= height[r]?Height[l]: height[r];9 }Ten returnwater; One}
C++
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4 intn = height.size (), L =0, R = N-1, water =0, MinHeight =0;5 while(L <r) {6 while(L < R && Height[l] <=minheight)7Water + = minheight-height[l++];8 while(R > L && height[r] <=minheight)9Water + = minheight-height[r--];TenMinHeight =min (height[l], height[r]); One } A returnwater; - } -};
Java
Public classSolution { Public intTrapint[] height) { intn = height.length, L = 0, r = n-1, water = 0, MinHeight = 0; while(L <r) { while(L < R && Height[l] <=minheight) Water+ = minheight-height[l++]; while(R > L && height[r] <=minheight) Water+ = minheight-height[r--]; MinHeight=math.min (Height[l], height[r]); } returnwater; }}
Python
1 classSolution:2 #@param {integer[]} height3 #@return {integer}4 defTrap (self, height):5n =len (height)6L, R, water, MinHeight = 0, n-1, 0, 07 whileL <r:8 whileL < R andHEIGHT[L] <=MinHeight:9Water + = MinHeight-Height[l]TenL + = 1 One whileR > L andHEIGHT[R] <=MinHeight: AWater + = MinHeight-Height[r] -R-= 1 -MinHeight =min (height[l], height[r]) the returnWater
[Leetcode] Trapping Rain Water