我已经为不相交集编写了这段代码
class DisjointSet{
HashMap<String,String> map;
public DisjointSet(){
map = new HashMap<>();
}
/*Time complexity for this is just O(1)
* because we are just inserting data into the HashMap
* */
public void makeSet(String s){
if(map.containsKey(s))
return;
map.put(s, s);
}
/*Time complexity for this is just O(1)
* because we are just inserting data into the HashMap
* */
public void Union(String p,String q){
if(!map.containsKey(p) || !map.containsKey(q))
return;
map.put(p, q);
}
/*This is where it gets interesting*/
public String Find(String s){
if(s.equals(map.get(s)))
return s;
String parent = this.Find(map.get(s));
map.put(s, parent);
return parent;
}
}
请注意,在 Find 方法中,我使用了路径压缩,但我没有在任何地方使用按等级联合。这里的时间复杂度会等于树的深度吗?