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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。