题解 | #接雨水问题#
接雨水问题
https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f?tpId=295&tqId=1002045&ru=/exam/intelligent&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Fintelligent%3FquestionJobId%3D10
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # max water # @param arr int整型一维数组 the array # @return long长整型 # class Solution: def maxWater(self, arr: list[int]) -> int: # write code here left= 0 right = len(arr) - 1 v=0 #左边和右边递增的时候都不考虑,移动指针 while left <right and arr[left+1]>=arr[left]: left+=1 while left<right and arr[right-1]>=arr[right] : right-=1 #height=min(left,right) while left <right: leftvalue=arr[left] rightvalue=arr[right] #当左边的值比右边的值小时,把左边的指针向右移动,如果arr[left]大于leftvalue,将leftvalue的值更新为该left,继续比较 if leftvalue <=rightvalue: while left<right and leftvalue >=arr[left]: v+=leftvalue-arr[left] left+=1 else: # 右指针类似 while left<right and rightvalue >=arr[right]: v+=rightvalue-arr[right] right-=1 return v