• 网络中节点间的连接状态
    • 网络是个抽象的概念: 用户之间形成的网络
  • 数学中的集合类实现

image.png
image.png
image.png

Quick Find

Union

image.png
image.png

image.png

Quick Union

image.png
image.png
image.png

基于size的优化

image.png

基于rank的优化

image.png
image.png
image.png
image.png
image.png

  1. package com.hoho.datastruture.unionfind;
  2. public class UnionFind5 implements UF {
  3. private int[] parent;
  4. //rank[i]表示以i为根的集合对应的层数
  5. private int[] rank;
  6. public UnionFind5(int size) {
  7. this.parent = new int[size];
  8. this.rank = new int[size];
  9. for (int i = 0; i < parent.length; i++) {
  10. parent[i] = i;
  11. rank[i] = 1;
  12. }
  13. }
  14. @Override
  15. public boolean isConnected(int p, int q) {
  16. return find(p) == find(q);
  17. }
  18. @Override
  19. public void unionElements(int p, int q) {
  20. int pRoot = find(p);
  21. int qRoot = find(q);
  22. if (pRoot == qRoot) {
  23. return;
  24. }
  25. //让元素个数比较小的根节点指向元素个数比较多的根节点
  26. if (rank[pRoot] < rank[qRoot]) {
  27. parent[pRoot] = qRoot;
  28. } else if (rank[pRoot] > rank[qRoot]) {
  29. parent[qRoot] = pRoot;
  30. } else {
  31. parent[qRoot] = pRoot;
  32. rank[pRoot] += 1;
  33. }
  34. }
  35. private int find(int p) {
  36. if (p < 0 && p >= parent.length)
  37. throw new IllegalArgumentException("p is out of bound.");
  38. while (p != parent[p]) {
  39. // 路径压缩
  40. parent[p] = parent[parent[p]];
  41. p = parent[p];
  42. }
  43. return p;
  44. }
  45. @Override
  46. public int getSize() {
  47. return parent.length;
  48. }
  49. }