题解 | #接雨水问题#

接雨水问题

https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f

class Solution:
    def maxWater(self , arr: List[int]) -> int:
        # write code here

        left = 0
        right = len(arr) - 1
        res = 0
        maxL = 0
        maxR = 0

        while left < right:
            maxL = max(maxL, arr[left])
            maxR = max(maxR, arr[right])

            if maxL < maxR:
                res += maxL - arr[left]
                left += 1
            else:
                res += maxR - arr[right]
                right -= 1

        return res

解题思路

  • 从两端遍历数组,获取左边最大值和右边最大值;
  • 当左边最大值小于右边最大值时,将左边最大值减去当前左指针指向的值,并且左指针向右移一位;
  • 否则,将右边最大值减去当前右指针指向的值,并且右指针往左边移一位。

复杂度

  • 时间复杂度为O(N);
  • 空间复杂度为O(1)。
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务