Dennis Leung

前端小天才智多星班进修中

  • 主页
  • 干货储物柜
所有文章 关于我

Dennis Leung

前端小天才智多星班进修中

  • 主页
  • 干货储物柜

并查集的实现

2020-06-03

用js实现一个并查集

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class UFS {
constructor() {
this.set = [];
}

//初始化节点
makeSet(x) {
this.set[x] = {
parent: x,
rank: 0,
};
}

//找出x的根节点
find(x) {
const node = this.set[x];
if (!node) {
return -1; //error
} else if (node.parent == x) {
return x;
} else {
return this.find(node.parent);
}
}

//判断x和y是否在同一个集合中
connected(x, y) {
return this.find(x) === this.find(y);
}

//合并两个集合
union(x, y) {
if (this.connected(x, y)) {
return true;
}
const xRoot = this.set[this.find(x)];
const yRoot = this.set[this.find(y)];
if (!xRoot || !yRoot) {
//error
return false;
}

if (xRoot.rank < yRoot.rank) {
//往rank大的元素挂载,这样不增加rank
xRoot.parent = y;
} else if (xRoot.rank > yRoot.rank) {
yRoot.parent = x;
} else {
xRoot.parent = y;
yRoot.rank += 1;
}

return true;
}
}
  • 算法
  • 数据结构
斐波那契求解效率对比
200. Number of Islands
© 2023 Dennis Leung
Hexo Theme Yilia by Litten

粤公网安备 44030502007083号

粤ICP备2021020087号

  • 所有文章
  • 关于我

tag:

  • leetcode
  • 算法
  • 并查集
  • JavaScript
  • 干货储物柜
  • Yii
  • php
  • Python
  • http
  • html
  • HTML
  • CSS
  • hexo
  • javascript
  • hybrid
  • 网络安全
  • Apple Script
  • 爬虫
  • 微信公众号
  • css
  • 数据结构
  • 编译原理
  • 位运算
  • 干活储物柜
  • 移动开发

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

不思进取的前端开发攻城狮。
梦想是躺着也能拯救世界。