我的DisjointSets代码的时间/空间复杂度是多少

时间:2017-02-13 16:50:09

标签: algorithm data-structures time-complexity big-o disjoint-sets

我为Disjoint sets编写了这段代码

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方法中,我使用了路径压缩,但我没有在任何地方使用union。 这里的时间复杂度是否等于树的深度?

0 个答案:

没有答案