leetcode practice - python3 (3)

48 篇文章 0 订阅
15 篇文章 0 订阅

53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

思路:从头开始遍历,维护一个当前的和及最大值,如果加上当前数字还比当前数字小,则从头开始计算和。

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0

        cur, ans = nums[0], nums[0] 
        for n in nums[1: ]:
            cur += n
            if cur < n:
                cur = n
            if cur > ans:
                ans = cur

        return ans

Beat 99.57% python3 2018-05-10

104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:
Given binary tree [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
return its depth = 3.

思路:递归求左右子树高度最大值

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0

        ans = 1 + max(self.maxDepth(root.left), self.maxDepth(root.right));
        return ans

Beat 77.46% python3 2018-05-11

尝试非递归:维护每个节点的高度,子节点的高度则为父节点高度+1

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0

        q = collections.deque()
        ans = 0
        q.append((root, 1))

        while q:
            c = q.popleft()
            if c[0].left != None:
                q.append((c[0].left, c[1]+1))
            if c[0].right != None:
                q.append((c[0].right, c[1]+1))
            ans = max(ans, c[1])

        return ans

Beat 77.46% python3 2018-05-11

优化:分层遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0

        q = collections.deque()
        ans = 0
        q.append(root)

        while q:
            ans += 1
            children = collections.deque()
            for n in q:
                if n.left:
                    children.append(n.left)
                if n.right:
                    children.append(n.right)
            q = children

        return ans

Beat 95.76% python3 2018-05-11

list代替deque:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0

        q = []
        ans = 0
        q.append(root)

        while q:
            ans += 1
            children = []
            for n in q:
                if n.left:
                    children.append(n.left)
                if n.right:
                    children.append(n.right)
            q = children

        return ans

Beat 99.82% python3 2018-05-11

101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.

思路:递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def isMirror(left, right):
            if left == None or right == None:
                return left == right

            return left.val == right.val and isMirror(left.left, right.right) and isMirror(left.right, right.left)

        return root == None or isMirror(root.left, root.right)

Beat 97.77% python3 2018-05-12

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def isMirror(left, right):
            if left == None and right == None:
                return True
            if left == None or right == None:
                return False

            return left.val == right.val and isMirror(left.left, right.right) and isMirror(left.right, right.left)

        return root == None or isMirror(root.left, root.right)

Beat 100.0% python3 2018-05-12

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root == None:
            return []

        q = [root]
        ans= [[root.val]]

        while q:
            next_level = []
            values = []
            for n in q:
                if n.left:
                    next_level.append(n.left)
                    values.append(n.left.val)
                if n.right:
                    next_level.append(n.right)
                    values.append(n.right.val)

            q = next_level
            if values:
                ans.append(values)

        return ans

Beat 100.0% python3 2018-05-12

70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

思路:DP

class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 2:
            return n

        dp = [ 0 for i in range(n+1) ]
        dp[0] = dp[1] = 1

        for i in range(2, n+1):
            dp[i] = dp[i-1] + dp[i-2]

        return dp[n]

Beat 95.14% python3 2018-05-13

思路:存储中间结果的递归

class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        dict = {}
        def solve(n):
            if n <= 1:
                return 1
            if n in dict:
                return dict[n]
            else:
                ret = solve(n-1) + solve(n-2)
                dict[n] = ret
                return ret

        return solve(n)

Beat 95.14% python3 2018-05-13

思路:类似斐波那齐数列

class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 2:
            return n

        n1, n2 = 1, 2
        for i in range(3, n+1):
            n3 = n1 + n2
            n1 = n2
            n2 = n3

        return n2

Beat 100.0% python3 2018-05-13

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值