并查集是一种数据结构,该名字每一个字代表一个意思。

  1. 并,代表合并
  2. 查, 代表查找
  3. 集,代表这是一个以字典为基础的数据结构,它的基本功能是合并集合中的元素,查找集合中的元素。
  4. 并查集典型应用是关于连通分量的问题。
  5. 并查集解决增删查的问题,时间复杂度都是O(1)。

代码如下:

  1. class UnionCollection {
  2. private Map<Integer, Integer> father;
  3. private int nums = 0;
  4. public UnionCollection() {
  5. father = new HashMap<>();
  6. }
  7. public int find(int x) {
  8. int root = x;
  9. while (father.get(root) != null) {
  10. root = father.get(root);
  11. }
  12. return root;
  13. }
  14. public void add(int x) {
  15. if (!father.containsKey(x)) {
  16. father.put(x, null);
  17. }
  18. }
  19. public void merge(int x, int y) {
  20. int rootX = find(x);
  21. int rootY = find(y);
  22. if (rootX != rootY) {
  23. father.put(rootX, rootY);
  24. }
  25. }
  26. public boolean isConnected(int x, int y) {
  27. return find(x) == find(y);
  28. }
  29. public int getNums() {
  30. return nums;
  31. }
  32. }

参考文献

  1. https://leetcode-cn.com/problems/number-of-provinces/solution/python-duo-tu-xiang-jie-bing-cha-ji-by-m-vjdr/