题目

image.png

思路

  • 并查集

    代码

    1. public int[] findRedundantConnection(int[][] edges) {
    2. if (edges == null || edges.length == 0) return new int[0];
    3. int[] s = new int[edges.length + 1];
    4. Arrays.fill(s, -1);
    5. for (int[] edge : edges) {
    6. if (!union(s, edge[0], edge[1])) return edge;
    7. }
    8. return new int[0];
    9. }
    10. public boolean union(int[] s, int i, int j) {
    11. int ri = findFC(s, i), rj = findFC(s, j);
    12. if (ri == rj) return false;
    13. s[ri] = rj;
    14. return true;
    15. }
    16. public int findFC(int[] s, int i) {
    17. if (i < 0 || i >= s.length) return -1;
    18. if (s[i] < 0) return i;
    19. s[i] = findFC(s, s[i]);
    20. return s[i];
    21. }

    冗余连接