Union Find:

589. Connecting Graph

 public class ConnectingGraph {
//父节点数组
private int[] father = null; /*
* @param n: An integer
*/
public ConnectingGraph(int n) {
// do intialization if necessary
father = new int[n + 1];
for (int i = 1; i <= n; i++) {
father[i] = i;
}
} /*
* @param a: An integer
* @param b: An integer
* @return: nothing
*/
public void connect(int a, int b) {
// write your code here
int root_a = find(a);
int root_b = find(b);
if (root_a == root_b) {
return;
}
father[root_a] = root_b;
} /*
* @param a: An integer
* @param b: An integer
* @return: A boolean
*/
public boolean query(int a, int b) {
// write your code here
return find(a) == find(b);
} //union find 主要逻辑,实现找到每个节点的父节点,同时把寻找父节点的路径子节点都直接链接到root节点下
//为了减少记录path的空间分配,可以每次将路径中子节点指向父节点的下一个节点,同样可以实现路径压缩
public int find(int a) {
if (father[a] == a) {
return a;
}
int i = a;
while (father[i] != i) {
int b = father[i];
father[i] = father[b];
i = b;
}
return i;
}
}

590. Connecting Graph II

 public class ConnectingGraph2 {
private int[] father = null;
private int[] size = null; /*
* @param n: An integer
*/
public ConnectingGraph2(int n) {
// do intialization if necessary
father = new int[n + 1];
size = new int[n+1];
for (int i = 1; i <= n; i++) {
father[i] = i;
size[i] = 1;
}
} /*
* @param a: An integer
* @param b: An integer
* @return: nothing
*/
public void connect(int a, int b) {
// write your code here
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b) {
father[root_a] = root_b;
size[root_b] += size[root_a];
}
} /*
* @param a: An integer
* @return: An integer
*/
public int query(int a) {
// write your code here
int root_a = find(a);
return size[root_a];
} public int find(int a) {
if (father[a] == a) {
return a;
} Set<Integer> path = new HashSet<>();
int i = a;
while (father[i] != i) {
path.add(i);
i = father[i];
}
for (int num : path) {
father[num] = i;
} return i; }
}

591. Connecting Graph III

 public class ConnectingGraph3 {
/**
* @param a: An integer
* @param b: An integer
* @return: nothing
*/
private int[] father = null;
private int count = 0; public ConnectingGraph3(int n) {
father = new int[n + 1];
for (int i = 1; i <= n; i++) {
father[i] = i;
}
count = n;
} public void connect(int a, int b) {
// write your code here
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b) {
father[root_a] = root_b;
count--;
}
} /**
* @return: An integer
*/
public int query() {
// write your code here
return count;
} public int find(int a) {
if (father[a] == a) {
return a;
}
int i = a;
while (father[i] != i) {
int b = father[i];
father[i] = father[b];
i = b;
}
return i;
}
}

1070. Accounts Merge(二刷复习)

 public class Solution {
/**
* @param accounts: List[List[str]]
* @return: return a List[List[str]]
*/
//integer对应accounts的index
Map<Integer, Integer> father = new HashMap<>(); public List<List<String>> accountsMerge(List<List<String>> accounts) {
// write your code here
List<List<String>> res = new ArrayList<>();
if (accounts == null || accounts.size() == 0) {
return res;
}
Map<String, List<Integer>> emailToIds = buildEmailToIds(accounts);
for (Map.Entry<String, List<Integer>> entry : emailToIds.entrySet()) {
List<Integer> ids = entry.getValue();
if (ids != null && ids.size() != 0) {
for (int i = 0; i < ids.size(); i++) {
union(ids.get(i), ids.get(0));
}
}
} Map<Integer, Set<String>> idToEmails = buildIdToEmails(accounts);
for (Map.Entry<Integer, Set<String>> entry : idToEmails.entrySet()) {
List<String> mergeList = new ArrayList<>();
List<String> accountList = new ArrayList<>(entry.getValue());
Collections.sort(accountList);
String user = accounts.get(entry.getKey()).get(0);
mergeList.add(user);
mergeList.addAll(accountList);
res.add(mergeList);
} return res;
} public Map<String, List<Integer>> buildEmailToIds(List<List<String>> accounts) {
Map<String, List<Integer>> res = new HashMap<>();
for (int i = 0; i < accounts.size(); i++) {
if (accounts.get(i) == null || accounts.get(i).size() <= 1) {
continue;
}
father.put(i, i);
List<String> emails = accounts.get(i);
for (int j = 1; j < emails.size(); j++) {
List<Integer> ids = res.get(emails.get(j));
if (ids == null) {
ids = new ArrayList<>();
}
ids.add(i);
res.put(emails.get(j), ids);
}
}
return res;
} public Map<Integer, Set<String>> buildIdToEmails(List<List<String>> accounts) {
Map<Integer, Set<String>> idToEmails = new HashMap<>();
for (int i = 0; i < accounts.size(); i++) {
int root_id = find(i);
Set<String> emails = idToEmails.get(root_id);
if (emails == null) {
emails = new HashSet<>();
}
for (int j = 1; j < accounts.get(i).size(); j++) {
emails.add(accounts.get(i).get(j));
}
idToEmails.put(root_id, emails);
}
return idToEmails;
} public void union(int a, int b) {
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b) {
father.put(root_a, root_b);
}
} public int find(int a) {
if (father.get(a) == a) {
return a;
}
Set<Integer> path = new HashSet<>();
int i = a;
while (father.get(i) != i) {
path.add(i);
i = father.get(i);
}
for (int num : path) {
father.put(num, i);
}
return i;
} }

Union Find - 20181102 - 20181105的更多相关文章

  1. Hive 数仓中常见的日期转换操作

    (1)Hive 数仓中一些常用的dt与日期的转换操作 下面总结了自己工作中经常用到的一些日期转换,这类日期转换经常用于报表的时间粒度和统计周期的控制中 日期变换: (1)dt转日期 to_date(f ...

  2. SQL Server-聚焦UNIOL ALL/UNION查询(二十三)

    前言 本节我们来看看有关查询中UNION和UNION ALL的问题,简短的内容,深入的理解,Always to review the basics. 初探UNION和UNION ALL 首先我们过一遍 ...

  3. SQL 提示介绍 hash/merge/concat union

    查询提示一直是个很有争议的东西,因为他影响了sql server 自己选择执行计划.很多人在问是否应该使用查询提示的时候一般会被告知慎用或不要使用...但是个人认为善用提示在不修改语句的条件下,是常用 ...

  4. LINQ to SQL语句(8)之Concat/Union/Intersect/Except

    适用场景:对两个集合的处理,例如追加.合并.取相同项.相交项等等. Concat(连接) 说明:连接不同的集合,不会自动过滤相同项:延迟. 1.简单形式: var q = ( from c in db ...

  5. SQLServer-----Union,Union All的使用方法

    转载: http://blog.csdn.net/kiqinie/article/details/8132485 select a.Name from Material as a union sele ...

  6. 假如 UNION ALL 里面的子句 有 JOIN ,那个执行更快呢

    比如: select id, name from table1 where name = 'x' union all select id, name from table2 where name =  ...

  7. sql union和union all的用法及效率

    UNION指令的目的是将两个SQL语句的结果合并起来.从这个角度来看, 我们会产生这样的感觉,UNION跟JOIN似乎有些许类似,因为这两个指令都可以由多个表格中撷取资料. UNION的一个限制是两个 ...

  8. 【oracle】union、union all、intersect、minus 的用法及区别

    一.union与union all 首先建两个view create or replace view test_view_1 as as c from dual union as c from dua ...

  9. sql with as union all

    WITH RPL (FId,Fname,Forder) AS ( SELECT ment.deptno,ment.deptname,ment.orderno FROM JTERP..fg_depart ...

随机推荐

  1. Ubuntu 14.04 安装配置强大的星际译王(stardict)词典

    转载http://blog.csdn.net/huyisu/article/details/53437931

  2. WCF项目问题1-找不到类型“WCFService.Service1”,它在 ServiceHost 指令中提供为 Service 特性值,或在配置元素 system.serviceModel/serviceHostingEnvironment/serviceActivations 中提供。

    找不到类型“WCFService.Service1”,它在 ServiceHost 指令中提供为 Service 特性值,或在配置元素 system.serviceModel/serviceHosti ...

  3. [GO]猜数字的小游戏

    随机生成四位数字,然后用户输入四位数字,然后根据提示一步步猜到随机数 package main import ( "math/rand" "time" &quo ...

  4. sql2008调试存储过程

    拿上篇存储过程为例: 在意个窗口里面写上exec Proc_MoveUpOrDown2 'id',3,1,'tableName,'orderid' 按F11,有个黄色的箭头会指向该行, 再按F11会跳 ...

  5. word 2013如何从某一页开始插入页码

    把光标移入要插入页面的最前面 插入分页符 在要插入页码的页脚双击打开页脚设计 取消页脚和前面页眉的链接 插入页码

  6. 【转】SSH指南

    OpenSSH OpenSSH 是 SSH (Secure SHell) 协议的免费开源实现.它用安全.加密的网络连接工具代替了 telnet.ftp. rlogin.rsh 和 rcp 工具.Ope ...

  7. delphi 数组的使用

    delphi中数组就跟string使用类似,数组分为:动态数组和静态数组 还可根据数据的功能分为:数组(一维数组).二维数组.三维数组...静态数组: 固定长度,内容需要定义时添加.动态数组: 故名思 ...

  8. 使用Sencha Cmd创建脚本框架

    从Ext JS 4.1.1a 开始,为了配合 Sencha Touch开发  而设计了 Sencha Cmd这个跨平台的命令行工具. 要使用Sencha Cmd,必须先安装好 Java Run-tim ...

  9. js任意位数求和

    <script> //任意位数求和 function sum(){ if(arguments.length==1) { console.log(arguments[0]) return; ...

  10. 微软和Google的盈利模式对比分析

    一: 微软和Google是世界上最成功科技巨头之一,但他们之间却有着不同的产品和业务,二者的盈利方式也各有不同,本文将分析和探讨的二者盈利模式的异同. 微软的盈利模式 在1975年由大学肄业的Bill ...