42. 接雨水.py 585 B

12345678910111213141516171819202122
  1. from typing import List
  2. class Solution:
  3. def trap(self, height: List[int]) -> int:
  4. res = 0
  5. left, right = 0, len(height) - 1
  6. lMax, rMax = 0, 0
  7. while left < right:
  8. lMax = max(lMax, height[left])
  9. rMax = max(rMax, height[right])
  10. if lMax < rMax:
  11. res += lMax - height[left]
  12. left += 1
  13. else:
  14. res += rMax - height[right]
  15. right -= 1
  16. return res
  17. if __name__ == '__main__':
  18. print(Solution().trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]))