题目

接雨水 - 图1

解题思路

接雨水 - 图2

代码

  1. class Solution {
  2. public int trap(int[] height) {
  3. int ans = 0;
  4. int left = 0, right = height.length - 1;
  5. int leftMax = 0, rightMax = 0;
  6. while (left < right) {
  7. leftMax = Math.max(leftMax, height[left]);
  8. rightMax = Math.max(rightMax, height[right]);
  9. if (height[left] < height[right]) {
  10. ans += leftMax - height[left];
  11. ++left;
  12. } else {
  13. ans += rightMax - height[right];
  14. --right;
  15. }
  16. }
  17. return ans;
  18. }
  19. }