2.5 Union Find/ Trie Tree

并查集:集合查询合并 支持O(1)find/O(1)union

Union Find

并查集的操作

1. 查询是否在同一个集合 Find (递归? 非递归?):O(1) find

1. 合并集合 Union: O(1) union

严谨地说:log*n

templete

class UnionFind:
    self.father = []
    def self.find(x):
        if self.father[x] == x:
            return x
        self.father[x] = find(self.father[x])
        return self.father[x]
        
    def self.union(a,b):
        root_a = self.find(a)
        root_b = self.find(b)
        if root_a != root_b:
            father[root_a] = root_b
    
    

application(graph)

Connecting Graph问题的总结

• 并查集原生操作:

•查询两个元素是否在同一个集合内 •合并两个元素所在的集合

• 并查集的派生操作:

•查询某个元素所在集合的元素个数 •查询当前集合的个数

Number of Connected Components in an Undirected Graph

Number of Islands

Number of Islands II

Number of Distinct Islands

* Graph Valid Tree

* Surrounded Regions

Trie Tree

1.考点:

Trie直接实现 利用Trie树前缀特性解题 矩阵类字符串一个一个字符深度遍历的问题

2. Hash vs Trie

时间复杂度Hash O(1) 是对于一个字符串

1.time complexity: same

2.space: trie < hash e.g.[a, aa, aaa, aaaa]

3.properties: hash is easier

Implement Trie

2.利用Trie树前缀特性解题:

Design Add and Search Words Data Structure

3. 矩阵类字符串一个一个字符深度遍历的问题(DFS+TRIE)

•DFS 树 和 Trie树同时遍历

Word Search II

Word Square

Last updated