【Leetcode】42. Trapping Rain Water

痛定思痛。 2022-03-08 00:35 240阅读 0赞

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.

rainwatertrap.png
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

  1. Input: [0,1,0,2,1,0,1,3,2,1,2,1]
  2. Output: 6

题目大意:

根据已给的列表找出其中能够装水的部分,并求出储水量。

解题思路:

我将这个过程分成两个部分:(1)正向遍历这个序列,此时我们可以找出储水的部分都是左边的边界比右边的边界低或者一样高的区域。因此这些的判断条件都是①、下一个位置比当前的低则是Left ②、当前位置比Left高则为Right。

(2)反向遍历,我们可以找出储水的部分都是右边的边界比左边的边界低的区域。

两次相加就可以得出最终答案。

  1. class Solution:
  2. def trap(self, height: List[int]) -> int:
  3. height.append(0)
  4. # print(height)
  5. state = False
  6. ans = 0
  7. R, L = 0, 0
  8. for i in range(len(height)-1):
  9. if state == False:
  10. if height[i] <= height[i+1]:
  11. continue
  12. else:
  13. state = True
  14. L = i
  15. continue
  16. else:
  17. if height[i] < height[L]:
  18. R = i
  19. else:
  20. R = R + 1
  21. tmp_min = height[L]
  22. if tmp_min > height[R]:
  23. tmp_min = height[R]
  24. tmp_ans = 0
  25. for j in range(L+1,R):
  26. tmp_ans += (tmp_min - height[j])
  27. ans += tmp_ans
  28. state = False
  29. if state == False:
  30. if height[i] <= height[i + 1]:
  31. continue
  32. else:
  33. state = True
  34. L = i
  35. continue
  36. state = False
  37. R, L = 0, 0
  38. height_re = height[:len(height)-1]
  39. # height_re.append(0)
  40. height_re.reverse()
  41. height_re.append(0)
  42. for i in range(len(height_re)-1):
  43. if state == False:
  44. if height_re[i] <= height_re[i+1]:
  45. continue
  46. else:
  47. state = True
  48. L = i
  49. continue
  50. else:
  51. if height_re[i] <= height_re[L]:
  52. R = i
  53. else:
  54. # 找槽完毕
  55. R = R + 1
  56. tmp_min = height_re[L]
  57. if tmp_min > height_re[R]:
  58. tmp_min = height_re[R]
  59. tmp_ans = 0
  60. for j in range(L+1,R):
  61. tmp_ans += (tmp_min - height_re[j])
  62. ans += tmp_ans
  63. state = False
  64. if state == False:
  65. if height_re[i] <= height_re[i + 1]:
  66. continue
  67. else:
  68. state = True
  69. L = i
  70. continue
  71. if R == 0 and L == 0:
  72. return 0
  73. return ans

发表评论

表情:
评论列表 (有 0 条评论,240人围观)

还没有评论,来说两句吧...

相关阅读