1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public: int trap(vector<int>& height) { int n = height.size(); if (n < 3) return 0; int left = 0, right = n - 1, leftMax = 0, rightMax = 0; int ans = 0; while (left < right) { if (height[left] < height[right]) { if (height[left] < leftMax) ans += leftMax - height[left]; else leftMax = height[left]; ++left; } else { if (height[right] < rightMax) ans += rightMax - height[right]; else rightMax = height[right]; --right; } } return ans; } };
|