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. python3--生成器并行运算

    # Auther: Aaron Fan """def consumer(name): print("%s 准备吃包子啦!" % name) while ...

  2. 通过javascript的日期对象来得到当前的日期

    var currentDate = new Date(); var weekday = ["星期日", "星期一", "星期二", &quo ...

  3. ORCHARD学习教程-介绍

    ORCHARD 是什么? Orchard 是由微软公司创建,基于 ASP.NET MVC 技术的免费开源内容管理系统: 可用于建设博客.新闻门户.企业门户.行业网站门户等各种网站 简单易用的后台界面 ...

  4. .net core MVC 通过 Filters 过滤器拦截请求及响应内容

    前提: 需要nuget   Microsoft.Extensions.Logging.Log4Net.AspNetCore   2.2.6: Swashbuckle.AspNetCore 我暂时用的是 ...

  5. WinForm中自定义搜索框(水印、清空按钮、加载中图标)

    public partial class CustomSearchBar : TextBox { private readonly Label lblwaterText = new Label(); ...

  6. 解决eclipse中启动Tomcat成功但是访问不了Tomcat问题

    自己搭建了一个springMVC项目,中间出了一些问题,在排查问题的过程中发现eclipse成功启动了Tomcat,但是在浏览器中输入localhost:8080却给我一个冷冷的404,我以为是Tom ...

  7. Linux下启动Tomcat项目

    在Linux下启动Tomcat项目方法:将war包放进Tomcat的wabapp目录下,进入tomcat目中的bin目录中,运行命令./startup.sh 回车就可以了

  8. docker--基本命令

    仅做学习参考,可能有误 part1:启动docker服务 在Windows上使用MySQL时候,有时无法直接使用MySQL -uroot -p 来进入MySQL,这是因为我们没有启动会MySQL服务此 ...

  9. dubbo服务治理中间件,zookeeper注册中心 安装配置

    对传统项目架构进行拆分: 集群概念: 面向服务分布式架构: 服务层提供被注册的对象需要实现序列化接口Serializable: 配置表现层和服务层: 依赖包: 服务层: <!-- 定义dubbo ...

  10. 文件参数化-utp框架之根据yaml文件自动生成python文件+utp运行用例

    根据yaml文件自动生成python文件 utp框架: bin目录:存放执行文件(run.py) cases目录:存放生成的用例的python文件(该目录下的文件为根据data目录下的测试用例生成的p ...