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. vuex 数据绑定

    操作文档: 安装vuex: cnpm install vuex --save   文档介绍: https://vuex.vuejs.org/guide/modules.html   import Vu ...

  2. Part5核心初始化_lesson1---异常向量表

    1.1异常 异常向量: 异常向量表: 代码的编写 start.S文件 gboot.lds链接器脚本文件 makefile工程文件:

  3. excel中COUNTIF的使用

    =(COUNTIF(D9:AH9,"●")+COUNTIF(D7:AH7,"●"))*0.5

  4. 线程同步synchronized,wait,notifyAll 测试示例

    https://www.cnblogs.com/LipeiNet/p/6475851.html 一  synchronized synchronized中文解释是同步,那么什么是同步呢,解释就是程序中 ...

  5. EBS取Web字段SQL操作文档

    1)  安全性—>责任-à定义 在这个路径下,输入责任名称,可以查询这个责任的请求组的名称 2)  organization_id 和 org_id的功能 3)  查找网页上的字段 Naviga ...

  6. Delphi xe7 up1 调用android振动功能

    Delphi xe7 up1 调用android振动功能 振动用到以下4个单元: Androidapi.JNI.App,Androidapi.JNIBridge,Androidapi.JNI.Os,A ...

  7. db2 中 SQL判断物理表是否存在、修改表名

    1.db2 中 SQL判断物理表是否存在 SELECT * FROM SYSIBM.SYSTABLES WHERE TID <> 0 AND Name = 'TABLE_NAME' AND ...

  8. PLSA的EM推导

    本文作为em算法在图模型中的一个应用,推导plsa的em算法. 1 em算法 em算法是解决一类带有隐变量模型的参数估计问题. 1.1 模型的定义 输入样本为,对应的隐变量为.待估计的模型参数为,目标 ...

  9. 【转】Android ActionBar完全解析,使用官方推荐的最佳导航栏(上)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/18234477 本篇文章主要内容来自于Android Doc,我翻译之后又做了些加工 ...

  10. Ubuntu在用root账户使用xftp连接时提示拒绝连接

    一般来说Linux不允许使用root账户连接,修改配置 vi /etc/ssh/sshd_config #Authentication: LoginGraceTime PermitRootLogin ...