[leetcode]684. Redundant Connection(Python)

[leetcode]684. Redundant Connection

题目描述

Category:Medium Tree

In this problem, a tree is an undirected graph that is connected and has no cycles.
The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, …, N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.
Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.
在这里插入图片描述

题目理解

在本题中,树是一个无向图,是连通的,但是没有循环。
给定的输入是一个图,它开始是一个有N个节点的树(具有不同的值1、2、…, N),增加了一条额外的边。添加的边有两个从1到N的不同顶点,并且不是已经存在的边。
结果图是一个二维的边数组。每个边的元素都是一对[u, v]和u < v,表示连接节点u和v的无向边。
返回一条可以删除的边,这样得到的图就是一个有N个节点的树。如果有多个答案,则返回给定二维数组中最后出现的答案。答案边[u, v]应该是相同的格式,u < v。

解题思路

并查集

实现了并查集查找根节点的代码,并且做了路径压缩,防止树太高导致查找根节点缓慢。
https://blog.csdn.net/fuxuemingzhu/article/details/80487064
无法静下心来看于是先放上补充链接叭
花花酱 并查集

class Solution:
    # Runtime: 52ms 87.35%  MemoryUsage: 14.1MB 28.57%
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        tree = [-1] * (len(edges) + 1)
        for edge in edges:
            a = self.findRoot(edge[0], tree)
            b = self.findRoot(edge[1], tree)
            if a != b:
                tree[a] = b
            else:
                return edge

    def findRoot(self, x, tree):
        if tree[x] == -1:
            return x
        else:
            root = self.findRoot(tree[x], tree)
            tree[x] = root
            return root

这道题有点不太走心了 等我状态好的时候静下心来再战!

Time

2020.3.27 一道题写了一天 头秃

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值