0305leetcode刷题5道python

这篇博客分享了5道LeetCode上的Python解题心得,涵盖了完全二叉树节点计算、最长递增子序列求解、单调递增函数的未知方程解法、矩阵内满足特定条件的正方形区域查找,以及如何在限制操作次数下最小化球分配的开销问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

222

题目描述:
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:
在这里插入图片描述
解答:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: TreeNode) -> int:
        '''
        return self.countNodes(root.left) + self.countNodes(root.right) + 1 if root else 0
        '''
        def find(path: str) -> bool:
            r = root
            for p in path:
                if p == '0':
                    if not r.left:  
                        return False
                    r = r.left
                else:
                    if not r.right:
                        return False
                    r = r.right
            return True

        h = 0
        p = root
        while p:
            h += 1
            p = p.left

        left, right = 2 ** (h - 1), 2 ** h - 1
        while left < right:
            mid = (left + right + 1) >> 1
            if find(bin(mid)[3:]):
                left = mid
            else:
                right = mid - 1
        return right

300

题目描述:
给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。

示例:
在这里插入图片描述
解答:

dp = [nums[0]]
        for i in range(1,len(nums)):
            if nums[i] > dp[-1]:
                dp.append(nums[i])
            else:
                left = 0
                right = len(dp) - 1
                while left < right:
                    mid = (left + right) // 2
                    if nums[i] > dp[mid]:
                        left = mid + 1
                    else:
                        right = mid
                dp[left] = nums[i]
        return len(dp)

1237

题目描述:
给你一个函数 f(x, y) 和一个目标结果 z,函数公式未知,请你计算方程 f(x,y) == z 所有可能的正整数 数对 x 和 y。满足条件的结果数对可以按任意顺序返回。
尽管函数的具体式子未知,但它是单调递增函数,也就是说:
f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
函数接口定义如下:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
你的解决方案将按如下规则进行评判:
判题程序有一个由 CustomFunction 的 9 种实现组成的列表,以及一种为特定的 z 生成所有有效数对的答案的方法。
判题程序接受两个输入:function_id(决定使用哪种实现测试你的代码)以及目标结果 z 。
判题程序将会调用你实现的 findSolution 并将你的结果与答案进行比较。
如果你的结果与答案相符,那么解决方案将被视作正确答案,即 Accepted 。

示例:
在这里插入图片描述
解答:

"""
   This is the custom function interface.
   You should not implement it, or speculate about its implementation
   class CustomFunction:
       # Returns f(x, y) for any given positive integers x and y.
       # Note that f(x, y) is increasing with respect to both x and y.
       # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
       def f(self, x, y):
  
"""

class Solution:
    def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:
        ans = []
        x = 1
        y = z
        while x <= z and y > 0:
            tmp = customfunction.f(x, y) 
            if tmp > z:
                y -= 1
            elif tmp < z:
                x += 1
            elif tmp == z:
                ans.append([x,y])
                x +=1
                y -=1
        return ans

1292

题目描述:
给你一个大小为 m x n 的矩阵 mat 和一个整数阈值 threshold。
请你返回元素总和小于或等于阈值的正方形区域的最大边长;如果没有这样的正方形区域,则返回 0 。

示例:
在这里插入图片描述
解答:

class Solution:
    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
        m, n, res = len(mat), len(mat[0]), 0
        tmp = [[0 for i in range(n+1)] for j in range(m+1)]
        def check(k):
            for i in range(k-1, m):
                for j in range(k-1, n):
                    if tmp[i][j] - tmp[i-k][j] - tmp[i][j-k] + tmp[i-k][j-k] <= threshold:
                        return True
            return False
        for i in range(m):
            for j in range(n):
                tmp[i][j] = tmp[i-1][j] + tmp[i][j-1] - tmp[i-1][j-1] + mat[i][j]
        l, r = 0, min(m, n)+1
        while l+1 < r:
            mid = (l+r) >> 1
            if check(mid):
                l = mid
            else:
                r = mid
        return l

1760

题目描述:
给你一个整数数组 nums ,其中 nums[i] 表示第 i 个袋子里球的数目。同时给你一个整数 maxOperations 。
你可以进行如下操作至多 maxOperations 次:
选择任意一个袋子,并将袋子里的球分到 2 个新的袋子中,每个袋子里都有 正整数 个球。
比方说,一个袋子里有 5 个球,你可以把它们分到两个新袋子里,分别有 1 个和 4 个球,或者分别有 2 个和 3 个球。
你的开销是单个袋子里球数目的 最大值 ,你想要 最小化 开销。
请你返回进行上述操作后的最小开销。

示例:
在这里插入图片描述
解答:

class Solution:
    def minimumSize(self, nums: List[int], maxOperations: int) -> int:
        l, r = 1, max(nums)
        while l < r:
            mid = (l + r) // 2
            t = 0
            for v in nums:
                t += (v - 1) // mid
            if t <= maxOperations:
                r = mid
            else:
                l = mid + 1
        return l
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值