[leetcode] 42. Trapping Rain Water @ python

原题

https://leetcode.com/problems/trapping-rain-water/

解法

双指针法, 用l, r定义左边和右边的index, min_height作为目前bar的高度,只能是左右两边高度的较小值, 然后两个指针都往中间刷, 遇到高度小于min_height的index时, 将该index能接到的水加到结果里.
Time: O(n)
Space: O(1)

代码

class Solution:
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        n = len(height)
        l, r, ans, min_height = 0, n-1, 0, 0
        while l < r:
            while l < r and height[l] <= min_height:
                ans += min_height - height[l]
                l += 1
            while l < r and height[r] <= min_height:
                ans += min_height - height[r]
                r -= 1
            min_height = min(height[l], height[r])
            
        return ans

你可能感兴趣的:(Leetcode)