• leetcode 684. Redundant Connection


    We are given a "tree" in the form of a 2D-array, with distinct values for each node.

    In the given 2D-array, each element pair [u, v] represents that v is a child of u in the tree.

    We can remove exactly one redundant pair in this "tree" to make the result a tree.

    You need to find and output such a pair. If there are multiple answers for this question, output the one appearing last in the 2D-array. There is always at least one answer.

    Example 1:
    Input: [[1,2], [1,3], [2,3]]
    Output: [2,3]
    Explanation: Original tree will be like this:
      1
     / 
    2 - 3
    Example 2:
    Input: [[1,2], [1,3], [3,1]]
    Output: [3,1]
    Explanation: Original tree will be like this:
      1
     / \
    2   3
    Note:
    The size of the input 2D-array will be between 1 and 1000.
    Every integer represented in the 2D-array will be between 1 and 2000.
    

    并查集,判断一下就好了 (比如线段[a,b],如果a在集合中,b也在集合中那么这条边就要删除)

    class Solution {
    public:
        int fa[1100];
        void init() {
            for (int i = 0; i < 1001; ++i) fa[i] = i;
        }
        int findfa(int x) {
            if (x == fa[x]) return x;
            return fa[x] = findfa(fa[x]);
        }
        int Union(int a, int b) {
            int x = findfa(a);
            int y = findfa(b);
            if (x == y) return 1;
            if (x < y) fa[y] = x;
            else fa[x] = y;
            return 0;
        }
        vector<int> findRedundantConnection(vector<vector<int>>& edges) {
            init();
            vector<int>v;
            for (int i = 0; i < edges.size(); ++i) {
                int a = edges[i][0];
                int b = edges[i][1];
                if (Union(a, b)) {
                    v.push_back(a);
                    v.push_back(b);
                }
            }
            return v;
        }
    };
    

    You are here!
    Your runtime beats 100.00 % of cpp submissions. 哈哈

  • 相关阅读:
    bootstrap的引用和注意事项
    css样式表的知识点总结
    数据去重宏脚本
    redis总结
    list对象中根据两个参数过滤数据
    dt常用类
    C#删除字符串最后一个字符的几种方法
    C#的split分割的举例
    数据库优化的几个注意点
    两种转换城市的方式
  • 原文地址:https://www.cnblogs.com/pk28/p/7589396.html
Copyright © 2020-2023  润新知