1. 程式人生 > 其它 >【LeetCode】684. Redundant Connection 冗餘連線(Medium)(JAVA)每日一題

【LeetCode】684. Redundant Connection 冗餘連線(Medium)(JAVA)每日一題

技術標籤:LeetCode 每日一題leetcode演算法java資料結構面試

【LeetCode】684. Redundant Connection 冗餘連線(Medium)(JAVA)

題目地址: https://leetcode.com/problems/redundant-connection/

題目描述:

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.

Example 1:

Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:
  1
 / \
2 - 3

Example 2:

Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be like this:
5 - 1 - 2
    |   |
    4 - 3

Note:

  • The size of the input 2D-array will be between 3 and 1000.
  • Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.

Update (2017-09-26):
We have overhauled the problem description + test cases and specified clearly the graph is an undirected graph. For the directed graph follow up please see Redundant Connection II). We apologize for any inconvenience caused.

題目大意

在本問題中, 樹指的是一個連通且無環的無向圖。

輸入一個圖,該圖由一個有著N個節點 (節點值不重複1, 2, …, N) 的樹及一條附加的邊構成。附加的邊的兩個頂點包含在1到N中間,這條附加的邊不屬於樹中已存在的邊。

結果圖是一個以邊組成的二維陣列。每一個邊的元素是一對[u, v],滿足u < v,表示連線頂點u和v的無向圖的邊。

返回一條可以刪去的邊,使得結果圖是一個有著N個節點的樹。如果有多個答案,則返回二維陣列中最後出現的邊。答案邊[u, v] 應滿足相同的格式u < v。

解題方法

  1. 採用並查集
  2. 如果兩個節點的父節點相同,說明兩個已經相連了,直接返回結果;如果兩個節點的父節點不同,就把兩個節點進行合併
class Solution {
    public int[] findRedundantConnection(int[][] edges) {
        int[] fa = new int[edges.length + 1];
        for (int i = 0; i < fa.length; i++) {
            fa[i] = i;
        }
        for (int i = 0; i < edges.length; i++) {
            if (find(fa, edges[i][0]) == find(fa, edges[i][1])) return edges[i];
            merge(fa, edges[i][0], edges[i][1]);
        }
        return new int[]{-1, -1};
    }

    private int find(int[] fa, int x) {
        if (fa[x] != x) return fa[x] = find(fa, fa[x]);
        return fa[x];
    }

    private void merge(int[] fa, int x, int y) {
        fa[find(fa, x)] = find(fa, y);
    }
}

執行耗時:1 ms,擊敗了87.99% 的Java使用者
記憶體消耗:38.8 MB,擊敗了34.46% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新