此题可以使用两种思路来解决:
- DFS
- Union-Find
以下是使用上一篇的数据结构Union-Find来处理的代码:
/** * LeetCode_146 * https://leetcode.com/problems/redundant-connection/description/ * https://www.youtube.com/watch?v=4hJ721ce010&list=LLaIZDn4w2rZnhRNMRMelhfg * */ class Solution { fun findRedundantConnection(edges: Array<IntArray>): IntArray { val size = edges.size val unionFindSet = UnionFindSet(size) for (edge in edges) { //there are 2 nodes in every edge //if they are have same parent, union() return false, so just return this edge if (!unionFindSet.union(edge[0], edge[1])) { return edge } } return IntArray(1) } }
原文地址:https://www.cnblogs.com/johnnyzhao/p/12310461.html
时间: 2024-11-13 22:31:16