Leetcode684. Redundant connections

Every day a Leetcode

Source of question: 684. Redundant connection

Solution 1: Union search

Because we need to determine whether two nodes are repeatedly connected, we can use union lookup to solve such problems.

Code:

/*
 * @lc app=leetcode.cn id=684 lang=cpp
 *
 * [684] 冗余连接
 */

// @lc code=start
class UnionFind
{
    
    
    vector<int> father, size;

public:
    UnionFind(int n) : father(n), size(n, 1)
    {
    
    
        // iota函数可以把数组初始化为 0 到 n-1
        iota(father.begin(), father.end(), 0);
    }
    int find(int x)
    {
    
    
        while (x != father[x])
        {
    
    
            // 路径压缩,使得下次查找更快
            father[x] = father[father[x]];
            x = father[x];
        }
        return x;
    }
    void connect(int p, int q)
    {
    
    
        int i = find(p), j = find(q);
        if (i != j)
        {
    
    
            // 按秩合并:每次合并都把深度较小的集合合并在深度较大的集合下面
            if (size[i] < size[j])
            {
    
    
                father[i] = j;
                size[j] += size[i];
            }
            else
            {
    
    
                father[j] = i;
                size[i] += size[j];
            }
        }
    }
    bool isConnected(int p, int q)
    {
    
    
        return find(p) == find(q);
    }
};
class Solution
{
    
    
public:
    vector<int> findRedundantConnection(vector<vector<int>> &edges)
    {
    
    
        int n = edges.size();
        UnionFind uf(n + 1);
        // uf.init();
        for (auto &edge : edges)
        {
    
    
            int u = edge[0], v = edge[1];
            if (uf.isConnected(u, v))
                return edge;
            uf.connect(u, v);
        }
        return {
    
    };
    }
};
// @lc code=end

result:

Insert image description here

Complexity analysis:

Time complexity: O(nlog⁡n), where n is the number of nodes in the graph. It is necessary to traverse n edges in the graph. For each edge, the ancestors of the two nodes need to be searched. If the ancestors of the two nodes are different, they need to be merged. 2 searches and at most 1 merge are required. A total of 2n searches and at most n merges are required, so the total time complexity is O(2nlog⁡n)=O(nlog⁡n). The union-find set here uses path compression, but does not use rank merging. The worst-case time complexity is O(nlog⁡n), and the average-case time complexity is still O(nα(n)). Among them, α is the inverse function of Ackermann function, and α(n) can be considered as a small constant.

Space complexity: O(n), where n is the number of nodes in the graph.

Guess you like

Origin blog.csdn.net/ProgramNovice/article/details/133382829