leetcode practice - python3 (12)

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

236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

Given the following binary search tree: root = [3,5,1,6,2,0,8,null,null,7,4]

__3_
/ \
_5 _1
/ \ / \
6 _2 0 8
/ \
7 4
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of of nodes 5 and 1 is 3.

Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself
according to the LCA definition.
Note:

All of the nodes’ values will be unique.
p and q are different and both values will exist in the binary tree.

思路:递归

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

class Solution:
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if root is None:
            return None

        if p == root or q == root:
            return root

        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)

        if not left:
            return right
        if not right:
            return left

        return root

Sorry. We do not have enough accepted submissions to show runtime distribution chart. python3 2018-06-02
Beat 42.47% python 2018-06-02

思路:从根找p,q的共同祖先

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

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        def isParent(p, c):
            if p is None:
                return False
            if p == c:
                return True
            return isParent(p.left, c) or isParent(p.right, c)

        if root is None or p == root or q == root:
            return root

        if isParent(p, q):
            return p
        if isParent(q, p):
            return q

        while root:
            if isParent(root.left, p) and isParent(root.left, q):
                root = root.left
            elif isParent(root.right, p) and isParent(root.right, q):
                root = root.right
            else:
                return root

        return root

Beat 96.01% python 2018-06-02

416. Partition Equal Subset Sum

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.

Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:
Input: [1, 2, 3, 5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.

思路:DP

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        sum_all = sum(nums)
        if sum_all & 1 != 0:
            return False

        target = sum_all // 2
        dp = [False] * (target+1)
        dp[0] = True

        for n in nums:
            for i in range(target, n-1, -1):
                dp[i] = dp[i] or dp[i-n]
                if dp[target]:
                    return True
        return dp[target]

Beat 75.94% python 2018-06-03

思路:DFS

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        def dfs(current, index):
            if current == target:
                return True

            for i in range(index, length):
                if current+nums[index] <= target and dfs(current+nums[index], i+1):
                    return True

            return False

        sum_all = sum(nums)
        if sum_all & 1 != 0:
            return False

        target = sum_all // 2
        length = len(nums)

        return dfs(0, 0)

超时

优化:排序及剪枝

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        def dfs(current, index):
            if current == target:
                return True

            for i in range(index, length):
                if current+nums[index] <= target and dfs(current+nums[index], i+1):
                    return True

            return False

        sum_all = sum(nums)
        if sum_all & 1 != 0:
            return False

        target = sum_all >> 1
        length = len(nums)

        nums.sort(reverse = True)
        if nums[0] > target:
            return False

        return dfs(0, 0)

Beat 93.23% python 2018-06-03

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        def dfs(current, index):
            for i in range(index, length):
                if current == nums[i]:
                    return True
                if current > nums[index] and dfs(current-nums[index], i+1):
                    return True

            return False

        sum_all = sum(nums)
        if sum_all & 1 != 0:
            return False

        target = sum_all >> 1
        length = len(nums)

        nums.sort(reverse = True)
        if nums[0] > target:
            return False

        return dfs(target, 0)

Beat 96.49% python 2018-06-03

46. Permutations

Given a collection of distinct integers, return all possible permutations.

Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

思路:DFS

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        def dfs(current):
            if len(current) == length:
                ans.append(current)
            else:
                for i in range(length):
                    if not visited[i]:
                        visited[i] = True
                        dfs(current+[nums[i]])
                        visited[i] = False

        ans = []
        length = len(nums)
        if length == 0:
            return ans

        visited = [False] * length
        dfs([])
        return ans

Beat 97.59% python3 2018-06-03

思路:python permutations

from itertools import *

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        return list(permutations(nums, len(nums)))

Beat 99.81% python3 2018-06-03

279. Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.

Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

思路1:DP
dp[i + j*j] = min(dp[i + j*j], dp[i] + 1)

    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        dp = [n] * (n+1)
        dp[0] = 0

        for j in range(1, 1+int(n**0.5)):
            for i in range(0, n+1-j*j):
                dp[i + j*j] = min(dp[i + j*j], dp[i] + 1)

        return dp[n]

Beat 33.10% python 2018-06-03

class Solution(object):
    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        dp = [0]
        while len(dp) <= n:
            dp += min(dp[-i*i] for i in range(1, int(len(dp)**0.5+1))) + 1,
        return dp[n]

Beat 61.42% python 2018-06-03

思路2:BFS

class Solution(object):
    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        import collections

        q = collections.deque()
        q.append((n, 0))
        while q:
            target, level = q.popleft()
            sqrt = int(target ** 0.5)
            while sqrt >= 1:
                left = target - sqrt*sqrt
                if left == 0:
                    return level+1
                if left > 0:
                    q.append((left, level+1))
                sqrt -= 1

Beat 68.13% python 2018-06-03

思路3:数学

    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        def isSquare(x):
            sqrt = int(x ** 0.5)
            return sqrt*sqrt == x

        if isSquare(n):
            return 1

        # while n % 4 == 0: n /= 4
        while n & 3 == 0:
            n >>= 2

        if n & 7 == 7:
            return 4

        sqrt = int(n ** 0.5)
        for i in range(1, sqrt+1):
            if isSquare(n - i*i):
                return 2

        return 3

Beat 100.0% python 2018-06-03

240. Search a 2D Matrix II

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Consider the following matrix:

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Example 1:
Input: matrix, target = 5
Output: true

Example 2:
Input: matrix, target = 20
Output: false

思路:从左下角开始,等于target则返回True,大于target则向上一行,小于target则向右一列

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        r = len(matrix) - 1
        c = 0

        cols = len(matrix[0])
        while r >= 0 and c < cols:
            if matrix[r][c] == target:
                return True

            if matrix[r][c] > target:
                r -= 1
            else:
                c += 1
        return False

Beat 95.84% python3 2018-06-03

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值