成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

323. Number of Connected Components in an Undirect

zsy888 / 1633人閱讀

摘要:題目鏈接這道題和是一個(gè)思路,一個(gè)初始化為,每次有新的就兩個(gè)節(jié)點(diǎn),如果兩個(gè)節(jié)點(diǎn)原來不在一個(gè)連通圖里面就減少并且連起來,如果原來就在一個(gè)圖里面就不管。用一個(gè)索引來做,優(yōu)化就是加權(quán)了,每次把大的樹的當(dāng)做,小的樹的作為。

323. Number of Connected Components in an Undirected Graph

題目鏈接:https://leetcode.com/problems...

這道題和numbers of islands II 是一個(gè)思路,一個(gè)count初始化為n,union find每次有新的edge就union兩個(gè)節(jié)點(diǎn),如果兩個(gè)節(jié)點(diǎn)(u, v)原來不在一個(gè)連通圖里面就減少count并且連起來,如果原來就在一個(gè)圖里面就不管。用一個(gè)索引array來做,union find優(yōu)化就是加權(quán)了,每次把大的樹的root當(dāng)做parent,小的樹的root作為child。

public class Solution {
    public int countComponents(int n, int[][] edges) {
        // union find
        int count = n;
        // array to store parent
        init(n, edges);
        for(int[] edge : edges) {
            int root1 = find(edge[0]);
            int root2 = find(edge[1]);
            if(root1 != root2) {
                union(root1, root2);
                count--;
            }
        }
        return count;
    }
    
    int[] map;
    private void init(int n, int[][] edges) {
        map = new int[n];
        for(int[] edge : edges) {
            map[edge[0]] = edge[0];
            map[edge[1]] = edge[1];
        }
    }
    
    private int find(int child) {
        while(map[child] != child) child = map[child];
        return child;
    }
    
    private void union(int child, int parent) {
        map[child] = parent;
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/66652.html

相關(guān)文章

  • Union-Find并查集算法學(xué)習(xí)筆記

    摘要:算法鏈接學(xué)習(xí)工具,,環(huán)境搭建在小伙伴的推薦下,這個(gè)學(xué)期開始上普林斯頓的算法課。一系列的整數(shù)對代表與相互連接,比如等,每一個(gè)整數(shù)代表了一個(gè)。我覺得這個(gè)可能也是并查集相關(guān)應(yīng)用。這學(xué)期繼續(xù)學(xué)習(xí)深入理解了就能明白了。 《算法》鏈接:1.5 Case Study: Union-Find學(xué)習(xí)工具:mac,java8,eclipse,coursera 環(huán)境搭建在小伙伴的推薦下,這個(gè)學(xué)期開始上普林斯頓...

    hzc 評論0 收藏0
  • 【Change Detection系列一】$digest 在Angular新版本中重生

    摘要:感謝您的閱讀如果喜歡這篇文章請點(diǎn)贊。它對我意義重大,它能幫助其他人看到這篇文章。對于更高級的文章,你可以在或上跟隨我。 I’ve worked with Angular.js for a few years and despite the widespread criticism I think this is a fantastic framework. I’ve started w...

    legendaryedu 評論0 收藏0
  • Find the Connected Component in the Undirected Gra

    Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its neighbors. (a connected component (or just component) of an undirected graph is a...

    Benedict Evans 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<