310. Minimum Height Trees(最小高度树)

本文通过一道难题探讨了图算法的应用,介绍了如何使用图数据结构解决树高度最小化问题的方法。通过对比不同容器的使用,深入剖析了算法实现过程中的难点。

个人认为这是一道挺难的题,本来以为是考察DFS、BFS的用法,因此一直构思如何遍历所有点并求出相应的树的高度并找出最小值,但写了很久发现还是写不出来。最后只能上网看一下这道题的思路,才知道这题重点考察图的运用。

这道题的算法思想是:先用二维向量构造出图,找出所有叶子结点,而连接这些叶子结点的父节点也要相应剪掉这些叶子结点;而当这些父节点变成叶子结点的时候,同样进行上述步骤。重复以上过程,直到只剩下不多于两个节点的根节点。

虽然算法乍看下来还是很简单的,但是实现起来我还是才了不少坑(C++学艺不精的结果)。一开始我用的是vector+list来存储图的,在循环遍历删除叶子结点时一直报错,结果发现是for循环中使用iterator++会导致迭代器指向错误;更改之后仍然在同一位置报错,仔细查看原来是iterator.erase()会使原迭代器失效,因此需要将iterator.erase()返回的迭代器赋值给原迭代器才可以。顺利debug之后的代码如下,但是TLE:

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        if (edges.size() == 0) {
            vector<int> vec;
            vec.push_back(0);
            return vec;
        }
        vector<list<int>> graph(n, list<int>());
        queue<int> q;
        list<int>::iterator it;
        vector<int> res;
        int count = 0;
        for (auto t : edges) {
            graph[t.first].push_back(t.second);
            graph[t.second].push_back(t.first);
        }
        for (int i = 0; i < graph.size(); i++) {
            if (graph[i].size() == 1) {
                q.push(i);
            }
        }
        while (n - 2 > count) {
            int times = q.size();
            while (times--) {
                int tmp = q.front();
                int i;
                for (i = 0; i < graph.size(); i++) {
                    if (tmp != i) {
                        for (it = graph[i].begin(); it != graph[i].end(); it) {
                            if (tmp == *it) {
                                it = graph[i].erase(it);
                                if (graph[i].size() == 1) {
                                    q.push(i);
                                }
                            }
                            else
                                it++;
                        }
                    }
                    else
                        graph[i].erase(graph[i].begin());
                }
                q.pop();
                count++;
            }
        }
        while (!q.empty()) {
            res.push_back(q.front());
            q.pop();
        }
        return res;
    }
};
后来查资料发现list.size()的时间复杂度为O(n),因此使用这个函数会耗费太多时间,于是重新使用vector+set来作出图,但仍然是TLE:

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        if (edges.size() == 0) {
            vector<int> vec;
            vec.push_back(0);
            return vec;
        }
        vector<set<int>> graph(n, set<int>());
        queue<int> q;
        set<int>::iterator it;
        vector<int> res;
        int count = 0;
        for (auto t : edges) {
            graph[t.first].insert(t.second);
            graph[t.second].insert(t.first);
        }
        for (int i = 0; i < graph.size(); i++) {
            if (graph[i].size() == 1) {
                q.push(i);
            }
        }
        while (n - 2 > count) {
            int times = q.size();
            while (times--) {
                int tmp = q.front();
                int i;
                for (i = 0; i < graph.size(); i++) {
                    if (tmp != i) {
                        for (it = graph[i].begin(); it != graph[i].end(); it) {
                            if (tmp == *it) {
                                it = graph[i].erase(it);
                                if (graph[i].size() == 1) {
                                    q.push(i);
                                }
                            }
                            else
                                it++;
                        }
                    }
                    else
                        graph[i].erase(graph[i].begin());
                }
                q.pop();
                count++;
            }
        }
        while (!q.empty()) {
            res.push_back(q.front());
            q.pop();
        }
        return res;
    }
};
百思不得其解,最后还是去网上参考了别人的做法,发现erase时根本不需要两重循环,活用图能够极快的完成删除操作:

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        if (edges.size() == 0) {
            vector<int> vec;
            vec.push_back(0);
            return vec;
        }
        vector<set<int>> graph(n, set<int>());
        queue<int> q;
        set<int>::iterator it;
        vector<int> res;
        int count = 0;
        for (auto t : edges) {
            graph[t.first].insert(t.second);
            graph[t.second].insert(t.first);
        }
        for (int i = 0; i < graph.size(); i++) {
            if (graph[i].size() == 1) {
                q.push(i);
            }
        }
        while (n - 2 > count) {
            int times = q.size();
            while (times--) {
                int tmp = q.front();
                for (auto t : graph[tmp]) {
                    graph[t].erase(tmp);
                    if (graph[t].size() == 1) {
                        q.push(t);
                    }
                }
                q.pop();
                count++;
            }
        }
        while (!q.empty()) {
            res.push_back(q.front());
            q.pop();
        }
        return res;
    }
};
由于图能清楚快速找到某个元素所连接的其他节点,因此可以找出要删除节点所连接的其他节点,并且set能通过迭代器也能根据元素直接删除的特性,从图找出其他节点的set集合再快速erase需要删除的节点,能大量降低复杂度,可以轻松AC。

总的来说,这道题收获还是很大的,除了对图有了更深的理解之外,也了解了STL各种容器之间的差异以及自己对其认识的不足,更能加深对各个STL容器的理解,对今后的学习非常有帮助。

### C语言实现选择K棵树高度差最小的算法 该问题可以通过排序和滑动窗口技术来高效求解。以下是详细的解决方案: #### 1. 算法思路 为了找到从N棵树中选择K棵树使得它们的高度差最小,可以按照以下方法处理: - 首先对树的高度数组进行升序排序[^5]。 - 使用一个长度为K的滑动窗口遍历排序后的数组,计算每组连续K棵树的最大值与最小值之差,并记录其中的最小差异。 这种方法的核心在于通过排序减少不必要的比较次数,从而提高效率。 #### 2. 时间复杂度分析 - 排序操作的时间复杂度为 \( O(N \log N) \)[^6]。 - 滑动窗口仅需线性扫描一次数组,其时间复杂度为 \( O(N) \)[^7]。 因此整体时间复杂度为 \( O(N \log N) \),适合大多数实际应用场景。 #### 3. 实现代码 下面是完整的C语言实现代码: ```c #include <stdio.h> #include <stdlib.h> // 定义比较函数用于qsort排序 int compare(const void *a, const void *b) { return (*(int *)a - *(int *)b); } int findMinHeightDifference(int trees[], int N, int K) { if (K == 0 || N == 0) return 0; if (N < K) return -1; // 对树木高度数组进行排序 qsort(trees, N, sizeof(int), compare); // 初始化最小高度差变量 int minDiff = trees[K - 1] - trees[0]; // 使用滑动窗口查找最小高度差 for (int i = 0; i <= N - K; i++) { int currentDiff = trees[i + K - 1] - trees[i]; if (currentDiff < minDiff) { minDiff = currentDiff; } } return minDiff; } int main() { int trees[] = {9, 12, 5, 3, 18}; int N = sizeof(trees) / sizeof(trees[0]); int K = 4; int result = findMinHeightDifference(trees, N, K); printf("Minimum height difference is: %d\n", result); return 0; } ``` 此程序实现了所需功能并提供了测试数据作为示例输入。 #### 4. 关键点说明 - **排序**:使用标准库中的 `qsort` 函数完成数组排序[^8]。 - **边界条件**:当K等于零或大于总数N时返回特殊标志(-1表示错误情况)[^9]。 - **滑动窗口逻辑**:每次移动窗口都重新评估当前子序列内的最大最小值差距,并更新全局最优解[^10]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值