684. Redundant Connection

此题可以使用两种思路来解决:

  • 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)
    }
}

 

posted @ 2020-02-15 01:31  johnny_zhao  阅读(110)  评论(0编辑  收藏  举报