并查集是一种数据结构,该名字每一个字代表一个意思。
- 并,代表合并
- 查, 代表查找
- 集,代表这是一个以字典为基础的数据结构,它的基本功能是合并集合中的元素,查找集合中的元素。
- 并查集典型应用是关于连通分量的问题。
- 并查集解决增删查的问题,时间复杂度都是O(1)。
代码如下:
class UnionCollection {private Map<Integer, Integer> father;private int nums = 0;public UnionCollection() {father = new HashMap<>();}public int find(int x) {int root = x;while (father.get(root) != null) {root = father.get(root);}return root;}public void add(int x) {if (!father.containsKey(x)) {father.put(x, null);}}public void merge(int x, int y) {int rootX = find(x);int rootY = find(y);if (rootX != rootY) {father.put(rootX, rootY);}}public boolean isConnected(int x, int y) {return find(x) == find(y);}public int getNums() {return nums;}}
