LeetCode 684冗余连接 HERODING的LeetCode之路

在本问题中, 树指的是一个连通且无环的无向图。

输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, …, N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。

结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。

返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。

示例 1:

输入: [[1,2], [1,3], [2,3]]
输出: [2,3]
解释: 给定的无向图为:
1
/
2 - 3

示例 2:

输入: [[1,2], [2,3], [3,4], [1,4], [1,5]]
输出: [1,4]
解释: 给定的无向图为:
5 - 1 - 2
| |
4 - 3

注意:

输入的二维数组大小在 3 到 1000。
二维数组中的整数在1到N之间,其中N是输入数组的大小。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/redundant-connection
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:
发现这几天的每日一题都是并查集类性,真的特别锻炼并查集使用的能力,并查集的方法主要是两个,一个是find,即找到祖宗节点,一个是union,即合并节点,拥有共同的祖宗,为了得到最小生成书,只要找到绕了一圈拥有共同祖宗节点的节点,即可直接输出,代码如下:

class Solution {
    
    
public:
// 寻找祖宗节点
    int Find(vector<int>& parent, int index) {
    
    
        if (parent[index] != index) {
    
    
            parent[index] = Find(parent, parent[index]);
        }
        return parent[index];
    }
// 合并节点,即拥有共同的祖宗
    void Union(vector<int>& parent, int index1, int index2) {
    
    
        parent[Find(parent, index1)] = Find(parent, index2);
    }

    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
    
    
        int nodesCount = edges.size();
        vector<int> parent(nodesCount + 1);
        // 初始化各个节点的祖宗
        for (int i = 1; i <= nodesCount; ++i) {
    
    
            parent[i] = i;
        }
        for (auto& edge: edges) {
    
    
            int node1 = edge[0], node2 = edge[1];
            // 如果不是同一个祖宗
            if (Find(parent, node1) != Find(parent, node2)) {
    
    
                Union(parent, node1, node2);
            } else {
    
    
                // 是同一个祖宗,说明绕回来了
                return edge;
            }
        }
        return vector<int>{
    
    };
    }
};



/*作者:heroding
链接:https://leetcode-cn.com/problems/redundant-connection/solution/bing-cha-ji-xiang-jie-by-heroding-j2vg/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/112550918