150强访谈简单

冗余连接

“冗余连接”问题的详细指南和 Python 实现。

问题陈述

简单

在这个问题中,树是一个连通且没有环的无向图。

给定一个图,该图最初是一棵树,其中有 n 个节点,标记为从 1 到 n,并添加了一条附加边。添加的边具有从 1 到 n 中选择的两个不同顶点,并且不是已存在的边。该图表示为长度为n的数组边,其中edges[i] = [ai, bi]表示节点ai和bi之间存在无向边。

返回一条可以删除的边,以便生成的图是一个包含 n 个节点的树。如果有多个答案,则返回输入中最后出现的答案。

编写一个函数 findRedundantConnection(edges: List[List[int]]) -> List[int]

约束条件
  • n == len(edges)
  • 3 <= n <= 1000
  • edges[i].length == 2
  • 1 <= ai < bi <= n
  • ai != bi

示例

Example 1
Input
edges = [[1,2],[1,3],[2,3]]
Output
[2,3]
Explanation

Removing edge [2,3] breaks the cycle 1-2-3-1, leaving a valid tree 1-2 and 1-3.

Example 2
Input
edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output
[1,4]
Explanation

The cycle is 1-2-3-4-1. The last edge in the input that is part of this cycle is [1,4].

Need a Hint?
考虑使用特定于图的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。