LeetCode 42 Trapping Rain Water (C++, Python)
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given
Given
[0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.Solution C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Solution { public: int trap(vector<int>& height) { int ret = 0; if (height.empty()) return ret; vector<int> left(height.size(), 0); vector<int> right(height.size(), 0); int maxLeft = height[0]; for (int i = 1; i < height.size(); ++i) { maxLeft = max(maxLeft, height[i - 1]); left[i] = maxLeft; } int maxRight = height[height.size() - 1]; for (int i = height.size() - 2; i >= 0; --i) { maxRight = max(maxRight, height[i + 1]); right[i] = maxRight; } for (int i = 0; i < height.size(); ++i) { int tmp = min(left[i], right[i]) - height[i]; if (tmp > 0) ret += tmp; } return ret; } }; |
Solution Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Solution: # @param height, an integer[] # @return an integer def trap(self, height): ret = 0 if not height: return ret left = [0] * len(height) right = [0] * len(height) maxleft = height[0] for i in range(1, len(height)): maxleft = max(maxleft, height[i - 1]) left[i] = maxleft maxright = height[-1] for i in range(len(height) - 2, -1, -1): maxright = max(maxright, height[i + 1]) right[i] = maxright for i in range(len(height)): tmp = min(left[i], right[i]) - height[i] if tmp > 0: ret += tmp return ret |