代码随想录第31天

56. 合并区间

python 复制代码
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals.sort(key=lambda p: p[0])  # 按照左端点从小到大排序
        ans = []
        for p in intervals:
            if ans and p[0] <= ans[-1][1]:  # 可以合并
                ans[-1][1] = max(ans[-1][1], p[1])  # 更新右端点最大值
            else:  # 不相交,无法合并
                ans.append(p)  # 新的合并区间
        return ans

738.单调递增的数字

python 复制代码
class Solution:
    def monotoneIncreasingDigits(self, N: int) -> int:
        nums = list(str(N))
        length = len(nums)
        begin = 0
        # N 是否符合条件
        is_result = True
        max_num = float('-inf')
        
        # 从前往后观察
        for i in range(1, length):
            num = int(nums[i])
            pre_num = int(nums[i - 1])
            # 记录最大值
            if pre_num > max_num:
                begin = i - 1
                max_num = pre_num
            if pre_num > num:
                is_result = False
                break
        
        # 如果 N 本身符合条件,直接返回 N
        if is_result:
            return N
        
        # begin 位置减去 1,后面全部替换为 9
        nums[begin] = str(int(nums[begin]) - 1)
        for i in range(begin + 1, length):
            nums[i] = '9'
                    
        return int("".join(nums))

968.监控二叉树

python 复制代码
class Solution:
    def minCameraCover(self, root: Optional[TreeNode]) -> int:
        def dfs(node):
            if node is None:
                return inf, 0, 0  # 空节点不能安装摄像头,也无需被监控到
            l_choose, l_by_fa, l_by_children = dfs(node.left)
            r_choose, r_by_fa, r_by_children = dfs(node.right)
            choose = min(l_choose, l_by_fa) + min(r_choose, r_by_fa) + 1
            by_fa = min(l_choose, l_by_children) + min(r_choose, r_by_children)
            by_children = min(l_choose + r_by_children, l_by_children + r_choose, l_choose + r_choose)
            return choose, by_fa, by_children
        choose, _, by_children = dfs(root)  # 根节点没有父节点
        return min(choose, by_children)
相关推荐
卷无止境3 分钟前
终端里的AI辅助,一场正在发生的编程效率变革
后端·python
苏灿烤鱼4 分钟前
上下文写成文件系统,为什么向量还能静默丢?
python·github·agent
SamChan901 小时前
对比 4 种主流 PDF 文档解析方案:PyMuPDF vs pdfplumber vs Apache PDFBox vs 大模型 OCR
python·ai·pdf·ocr·apache·机器翻译
安_9 小时前
如何构建和使用向量索引?HNSW 和 IVF 有什么区别?
python·ai
counting money10 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
坚持学习前端日记11 小时前
Python SQLAlchemy ORM 从0到1精通实战手册(基础到复杂高阶)
数据库·python·oracle
北斗落凡尘11 小时前
LangGraph 入门实战(11)--输出模式
后端·python·langchain
雪碧聊技术11 小时前
安装Python(保姆级教程)
python·版本更新·python下载
++==12 小时前
JSON和Python的 四种核心容器
python·json
张龙68714 小时前
uv 全面指南:比 pip 快 100 倍的 Python 包管理器,从安装到团队落地
后端·python