zoukankan      html  css  js  c++  java
  • leetcode42 Trapping Rain Water

     1 """
     2 Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
     3 The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
     4 Example:
     5 Input: [0,1,0,2,1,0,1,3,2,1,2,1]
     6 Output: 6
     7 """
     8 """
     9 每个位置上积水的高度,应该等于min(左边最高的柱子高度,右边最高的柱子高度) -  这个位置上的柱子高度。
    10 所以先从左往右遍历把left_max数组生成,left_max[i]代表 height[i] 及其左侧最高的柱子高度。
    11 同理生成right_max。
    12 然后再遍历一次对于每个位置计算min(left_max[i], right_max[i]) - height[i]就好了
    13 """
    14 class Solution1:
    15     def trap(self, height):
    16         max_left = [0] * len(height)
    17         max_right = [0] * len(height)
    18         res = 0
    19         for i in range(len(height)):
    20             if i > 0:
    21                 max_left[i] = max(max_left[i - 1], height[i])
    22             else:
    23                 max_left[i] = height[i]
    24         for j in range(len(height) - 1, -1, -1):
    25             if j < len(height) - 1:
    26                 max_right[j] = max(max_right[j + 1], height[j])
    27             else:
    28                 max_right[j] = height[j]
    29         for k in range(len(height)):
    30             res += min(max_left[k], max_right[k]) - height[k]
    31         return res
    32 
    33 """
    34 自己的想法是创建i和j分别指向每个积水槽的两端
    35 积水的体积 = 集水槽的短边*底的长度-中间的每个值
    36 但主要卡在 i,j无法寻找
    37 我的想法是 height[i]>height[i-1] and height[i]>height[i+1]
    38 但对于[2, 0, 2]这种测试案例无法解决
    39 """
    40 class Solution2:
    41     def trap(self, height):
    42         n = len(height)
    43         i, j = 1, 0
    44         res = 0
    45         while i < n-1:
    46             if height[i] > height[i-1] and height[i] > height[i+1]:
    47                 j = i+1
    48                 neg = 0
    49                 while j < n - 2:
    50                     if not (height[j] > height[j - 1] and height[j] > height[j + 1]):
    51                         neg += height[j]
    52                         j += 1
    53                     else:
    54                         break
    55                 res += min(height[i], height[j]) * (j - i - 1) - neg
    56             i = j
    57         return res
  • 相关阅读:
    Burp suite
    CTF 压缩包分析
    PHP代码审计
    SQL注入
    常考文件包含漏洞
    PHP黑魔法
    CTF WEB笔记
    MsSQL数据库提权
    ATT&CK实战系列
    Linux访问控制
  • 原文地址:https://www.cnblogs.com/yawenw/p/12346187.html
Copyright © 2011-2022 走看看