• Leetcode刷题10.19——盛水最多的容器 & 相同的树


    leetcode 11 盛水最多的容器

      *输入为一个数组,输出为最大容量的值

      思路是,双指针法,一个从最左开始遍历,一个最右往回遍历,直到两指针相遇。每次移动的依据是要移动高度小的那个位置的指针(这样才能保证以后有可能遇到更大的容量)

      代码如下:

    class Solution:
        def maxArea(self, height: List[int]) -> int:
            if len(height) <= 2:
                return min(height)
            left = 0
            right = len(height)-1
            A = (len(height)-1) * min(height[left], height[right])
            while left < right:
                if left < right and height[left] <= height[right]:  #一定要注意别忘了“=”号,忘记这个有些用例会陷入死循环
                    left += 1
                elif left < right and height[left] > height[right]:
                    right -= 1
                A = max(A, min(height[left],height[right]) * (right - left))
            return A 

    leetcode 100 相同的树

       思路是DFS深度优先遍历,递归。需要注意是终止条件分为哪些情况:

    • 什么情况下判断到终点,两个节点相等——没有子树时
    • 什么情况下可以提前结束遍历——两个节点一个存在一个不存在,或两个节点连值都不相等时
    • 此外还需注意三个终止条件判断的顺序——先判断完存在,再判断值,最后else里是中间情况,即需要左右子树同时相等才是符合要求的
    class Solution:
        def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
            if not p and not q:
                return True
            elif not p or not q:
                return False
            elif p.val != q.val:
                return False
            else:
                return self.isSameTree(p.right,q.right) and self.isSameTree(p.left, q.left)
  • 相关阅读:
    code of C/C++(2)
    code of C/C++ (1)
    dll 的编写和使用
    Python基础练习-数据类型与变量part2
    Python基础练习-数据类型与变量
    python基础练习-循环
    Linux grep
    nginx反向代理
    正则表达式
    Linux samba ing
  • 原文地址:https://www.cnblogs.com/nekoneko-15/p/13849179.html
Copyright © 2020-2023  润新知