Middle-题目85:310. Minimum Height Trees

本文介绍了一种高效算法来找出使树高度最小的根节点。通过逐步移除度为1的节点,最终找到符合条件的节点。提供了两种Java实现方案并对比了它们的性能。

题目原文:
For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Example 1:
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]

    0
    |
    1
   / \
  2   3

return [1]
Example 2:
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

 0  1  2
  \ | /
    3
    |
    4
    |
    5

return [3, 4]
题目大意:
给出一个树,它的任何一个顶点都可以看做树的根节点,写一个函数,输出使得树高度最小的顶点的列表。
输入参数是顶点个数和边的列表(用二维数组表示)。
例如,输入n = 4, 边列表= [[1, 0], [1, 2], [1, 3]]
则以1为根节点的树的高度最小。
题目分析:
不管树有多复杂,使得高度最小的顶点至多有2个。(我也想不出证明过程……)
暴力解法是对每个节点求高度。这里有一个比较好的算法,即每轮去掉度为1的节点,直到顶点剩下1个或2个(显然不可能是3个或更多,因为没有环),那么这1个或2个节点即为所求。
源码:(language:java)

public class Solution {    
    public  List<Integer> findMinHeightTrees(int n, int[][] edges) {
        Map<Integer, Set<Integer>> adjList = new HashMap<Integer,Set<Integer>>();
        boolean[] isLeaf = new boolean[n];
        int[] degrees = new int[n];
        int nextVertical = 0, currentVerticals = n;
        for(int i = 0; i<n;i++)
            adjList.put(i, new HashSet<Integer>());
        for(int[] edge : edges) {
            adjList.get(edge[0]).add(edge[1]);
            degrees[edge[0]]++;
            adjList.get(edge[1]).add(edge[0]);
            degrees[edge[1]]++;
        }
        while(currentVerticals > 2) {
            for(int i = 0;i<n;i++) {
                if(degrees[i]==1) {
                    isLeaf[i] = true;
                }
            }
            for(int i = 0;i<n;i++) {
                if(isLeaf[i]) {
                    nextVertical = adjList.get(i).iterator().next();
                    degrees[i]--;
                    degrees[nextVertical]--;
                    adjList.get(i).remove(nextVertical);
                    if(degrees[i]==0)
                        currentVerticals--;
                    adjList.get(nextVertical).remove(i);
                    if(degrees[nextVertical]==0)
                        currentVerticals--;
                    isLeaf[i] = false;
                }
            }
        }
        List<Integer> list = new ArrayList<Integer>();
        for(Integer key : adjList.keySet()) {
            if(adjList.get(key).size()!=0)
                list.add(key);
        }
        if(n==1)
            list.add(0);
        if(currentVerticals==0)
            list.add(nextVertical);
        return list;
    }
}

这里给出discuss中一位大神给出的算法,思路是一样的,但省略了很多循环:

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        if (n == 1) 
            return Collections.singletonList(0);
        List<Set<Integer>> adj = new ArrayList<>(n);
        for (int i = 0; i < n; i++) 
            adj.add(new HashSet<>());
        for (int[] edge : edges) {
            adj.get(edge[0]).add(edge[1]);
            adj.get(edge[1]).add(edge[0]);
        }

        List<Integer> leaves = new ArrayList<>();
        for (int i = 0; i < n; i++)
            if (adj.get(i).size() == 1) leaves.add(i);

        while (n > 2) {
            n -= leaves.size();
            List<Integer> newLeaves = new ArrayList<>();
            for (int i : leaves) {
                int j = adj.get(i).iterator().next();
                adj.get(j).remove(i);
                if (adj.get(j).size() == 1) newLeaves.add(j);
            }
            leaves = newLeaves;
        }
        return leaves;
    }
}

成绩:
算法一(我写的):170ms,beats 14.07%,众数56ms,5.12%
算法二(from discuss):58ms,beats 68.02%
Cmershen的碎碎念:
这是leetcode里面第一个涉及图的题,图应该是数据结构里面的难点,因此这题的成绩很分散。同时说明,即使算法思路相同,内部实现细节不同也会导致成绩有很大差异。比如记录邻接表的时候人家用的是list的下标而不是使用Map的key值,而一直用leaves数组维护当前叶子节点而不是一直在数度,也是比较巧妙的。

内容概要:本文为《科技类企业品牌传播白皮书》,系统阐述了新闻媒体发稿、自媒体博主种草与短视频矩阵覆盖三大核心传播策略,并结合“传声港”平台的AI工具与资源整合能力,提出适配科技企业的品牌传播解决方案。文章深入分析科技企业传播的特殊性,包括受众圈层化、技术复杂性与传播通俗性的矛盾、产品生命周期影响及2024-2025年传播新趋势,强调从“技术输出”向“价值引领”的战略升级。针对三种传播方式,分别从适用场景、操作流程、效果评估、成本效益、风险防控等方面提供详尽指南,并通过平台AI能力实现资源智能匹配、内容精准投放与全链路效果追踪,最终构建“信任—种草—曝光”三位一体的传播闭环。; 适合人群:科技类企业品牌与市场负责人、公关传播从业者、数字营销管理者及初创科技公司创始人;具备一定品牌传播基础,关注效果可量化与AI工具赋能的专业人士。; 使用场景及目标:①制定科技产品全生命周期的品牌传播策略;②优化媒体发稿、KOL合作与短视频运营的资源配置与ROI;③借助AI平台实现传播内容的精准触达、效果监测与风险控制;④提升品牌在技术可信度、用户信任与市场影响力方面的综合竞争力。; 阅读建议:建议结合传声港平台的实际工具模块(如AI选媒、达人匹配、数据驾驶舱)进行对照阅读,重点关注各阶段的标准化流程与数据指标基准,将理论策略与平台实操深度融合,推动品牌传播从经验驱动转向数据与工具双驱动。
This is the style section, please modify and give me the full code <style> /* Custom Styles for Cart Page */ .cart-page-section { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 30px; } .cart-page-section table.cart { width: 100%; border-collapse: collapse; margin-bottom: 20px; } .cart-page-section table.cart th, .cart-page-section table.cart td { padding: 15px; text-align: left; border-bottom: 1px solid #eee; } .cart-page-section table.cart th { background-color: #f8f8f8; font-weight: bold; } /* 调整列宽 - 增加全选列宽度 */ .cart-page-section table.cart th.product-select, .cart-page-section table.cart td.product-select { width: 8%; /* 增加宽度 */ text-align: center; vertical-align: middle; white-space: nowrap; /* 防止文字换行 */ } .cart-page-section table.cart td.product-info { width: 37%; /* 微调其他列宽度 */ vertical-align: top; } .cart-page-section table.cart .product-info .product-image { float: left; margin-right: 15px; width: 100px; height: 100px; } .cart-page-section table.cart .product-info .product-image img { max-width: 100%; height: auto; display: block; } .cart-page-section table.cart .product-info .product-name { overflow: hidden; } /* 调整剩余列宽度 */ .cart-page-section table.cart td.product-price, .cart-page-section table.cart td.product-quantity, .cart-page-section table.cart td.product-subtotal { width: 15%; /* 三列平均分配剩余宽度 */ vertical-align: middle; } .cart-page-section table.cart td.product-remove { width: 5%; text-align: center; vertical-align: middle; } .cart-footer-actions { position: sticky; bottom: 0; background: #fff; padding: 15px; border-top: 1px solid #ddd; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); z-index: 1000; } .cart-footer-actions .button { padding: 10px 20px; margin-left: 10px; background-color: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background-color 0.3s; } .cart-footer-actions .button:hover { background-color: #d32f2f; } #partial-checkout { padding: 12px 24px; background-color: #2196F3; color: white; text-decoration: none; border-radius: 4px; display: inline-block; margin-top: 10px; transition: background-color 0.3s; } #partial-checkout:hover { background-color: #0b7dda; } .selected-summary { font-size: 16px; font-weight: bold; } .selected-summary p { margin: 0 0 10px 0; } /* Responsive styles */ @media (max-width: 768px) { .cart-page-section table.cart thead { display: none; } .cart-page-section table.cart td { display: block; width: 100% !important; text-align: right; padding: 10px; position: relative; padding-left: 50%; } .cart-page-section table.cart td::before { content: attr(data-title); position: absolute; left: 15px; font-weight: bold; text-align: left; } .cart-page-section table.cart .product-info .product-image { float: none; margin: 0 auto 10px; } .cart-footer-actions { position: sticky; bottom: 0; } .cart-footer-actions > div { flex-direction: column; align-items: flex-start; } .cart-footer-actions .selected-summary { margin-top: 20px; text-align: left; width: 100%; } /* 移动端调整全选列 */ .cart-page-section table.cart td.product-select::before { content: "选择"; } } </style>
08-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值