題目如下:
思路:
這道題我推薦使用雙指針的動態規劃方法求解,通過動態更新左右的最大高度(決定容量的是左右最大高度中較小的那一個),來獲取答案,可以單步調試看看求解的具體過程。
參考代碼:
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left = 0
right = len(height) - 1
res = 0
left_max = 0
right_max = len(height) - 1
while left < right:
if height[left] > height[right]:
if height[right_max] < height[right]:
right_max = right
right = right - 1
else:
res += height[right_max] - height[right]
right = right - 1
if height[left] <= height[right]:
if height[left_max] < height[left]:
left_max = left
left = left + 1
else:
res += height[left_max] - height[left]
left = left + 1
return res
源碼地址:
https://github.com/jediL/LeetCodeByPython
其它題目:[leetcode題目答案講解彙總(Python版 持續更新)]
(https://www.jianshu.com/p/60b5241ca28e)
ps:如果您有好的建議,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)