码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-42-接雨水

时间:2019-10-23 13:43:57      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:div   info   def   res   sel   col   pre   +=   inf   

题目描述:

技术图片

 

 第一次提交:

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-接雨水

标签:div   info   def   res   sel   col   pre   +=   inf   

原文地址:https://www.cnblogs.com/oldby/p/11725643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!