【Leetcode】1135. Connecting Cities With Minimum Cost

题目地址:

https://leetcode.com/problems/connecting-cities-with-minimum-cost/

给定一个带权无向图,图由给定一系列的边的方式给出。求其最小生成树的权和。如果不存在最小生成树则返回 − 1 -1 1

直接用Kruskal算法。对边按照边权由小到大排序,然后遍历边,只要不会产生环,就依次将边加入。代码如下:

import java.util.Arrays;

public class Solution {
    
    class UnionFind {
        private int[] parent;
        // group记录当前有多少个连通分量
        private int group;
    
        public UnionFind(int n) {
            parent = new int[n];
            for (int i = 0; i < parent.length; i++) {
                parent[i] = i;
            }
            group = n;
        }
        
        private int find(int x) {
            if (x != parent[x]) {
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }
        
        // 返回加入边(x, y)之后会不会产生环
        private boolean union(int x, int y) {
            int px = find(x), py = find(y);
            if (px == py) {
                return false;
            }
            
            parent[px] = py;
            
            // 将两个连通分量合并了之后连通分量个数少一个
            group--;
            return true;
        }
    
        public int getGroup() {
            return group;
        }
    }
    
    public int minimumCost(int N, int[][] connections) {
        Arrays.sort(connections, (c1, c2) -> Integer.compare(c1[2], c2[2]));
        
        int res = 0;
        UnionFind uf = new UnionFind(N);
        for (int[] connection : connections) {
            if (uf.union(connection[0] - 1, connection[1] - 1)) {
                res += connection[2];
            }
        }
        
        // 连通分量等于1说明找到了最小生成树,否则说明原图不连通,返回-1
        return uf.getGroup() == 1 ? res : -1;
    }
}

时间复杂度 O ( E log ⁡ E ) O(E\log E) O(ElogE)(主要花在排序上了),空间 O ( V ) O(V) O(V)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值