leetcode-42-接雨水

Posted 真不知道叫啥好

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-42-接雨水相关的知识,希望对你有一定的参考价值。

题目描述:

 

 第一次提交:

class Solution:
    def trap(self, height: List[int]) -> int:
        res = 0
        def helper(height):
            nonlocal res
            if len(height) <= 1:
                return
            queue = []
            for i in height:
                if queue and i >= queue[0]:
                    res += sum(queue[0] - j for j in queue)
                    queue = [i]
                else:
                    queue.append(i)
            helper(queue[::-1])
        helper(height)
        return res
            

方法一:动态规划: O(N) O(N)

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height: return 0
        n = len(height)
        max_left = [0] * n
        max_right = [0] * n
        max_left[0] = height[0]
        max_right[-1] = height[-1]
        # 找位置i左边最大值
        for i in range(1, n):
            max_left[i] = max(height[i], max_left[i-1])
        # 找位置i右边最大值
        for i in range(n-2, -1, -1):
            max_right[i] = max(height[i], max_right[i+1])
        #print(max_left)
        #print(max_right)
        # 求结果
        res = 0
        for i in range(n):
            res += min(max_left[i], max_right[i]) - height[i]
        return res

方法二:双指针 O(N) O(1)

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height: return 0
        left = 0
        right = len(height) - 1
        res = 0
        # 记录左右边最大值
        left_max = height[left]
        right_max = height[right]
        while left < right:
            if height[left] < height[right]:
                if left_max > height[left]:
                    res += left_max - height[left]
                else:
                    left_max = height[left]
                left += 1
            else:
                if right_max > height[right]:
                    res += right_max - height[right]
                else:
                    right_max = height[right]
                right -= 1 
        return res

方法三:栈 O(N)*

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height: return 0
        n = len(height)
        stack = []
        res = 0
        for i in range(n):
            #print(stack)
            while stack and height[stack[-1]] < height[i]:
                tmp = stack.pop()
                if not stack: break
                res += (min(height[i], height[stack[-1]]) - height[tmp]) * (i-stack[-1] - 1)
            stack.append(i)
        return res

 

以上是关于leetcode-42-接雨水的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 42. 接雨水

Leetcode 42 接雨水

[LeetCode] 42. 接雨水

Leetcode 42 接雨水

leetcode 42.接雨水

[leetcode] 42. 接雨水