Longest Consecutive Sequence (128)

1. Union Find

时间O(1)

空间O(n)

 

定义class。 注意rank

class UnionFind{
    Map<Integer, Integer> father;
    Map<Integer, Integer> rank;
    int max;
    
    public UnionFind(){
        father = new HashMap<>();
        rank = new HashMap<>();
        max = 0;
    }
    
    public void add(int n){
        if(father.containsKey(n)) return;
        father.put(n,n);
        rank.put(n,1);
        max = Math.max(max, 1);
    }
    
    public void union(int n, int m){
        if(!father.containsKey(n) || !father.containsKey(m)) return;
        int father_n = find(n);
        int father_m = find(m);
        if(father_n != father_m){
            if(rank.get(father_n) > rank.get(father_m)){
                father.put(father_m, father_n);
                rank.put(father_n, rank.get(father_n) + rank.get(father_m));
                max = Math.max(max, rank.get(father_n));
            }else{
                father.put(father_n, father_m);
                rank.put(father_m, rank.get(father_n) + rank.get(father_m));
                max = Math.max(max, rank.get(father_m));
            }
        }
    }
    public Integer find(int n){
        int father_n = father.get(n);
        if(father_n != n){
            father.put(n, find(father_n));
        }
        return father.get(n);
    }
}

主函数调用

 public int longestConsecutive(int[] nums) {
        if(nums == null || nums.length == 0){
            return 0;
        }
        
        UnionFind uf = new UnionFind();
        for(int i = 0 ; i < nums.length; ++i){
            uf.add(nums[i]);
            uf.union(nums[i]-1, nums[i]);
            uf.union(nums[i]+1, nums[i]);
        }
        return uf.max;
    }

 

2. 用set做

时间O(1)

空间O(n)

    public int longestConsecutive(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int result = 0;
        Set<Integer> set = new HashSet<>();
        for(int i : nums) set.add(i);
        for(int i : nums){
            if(!set.contains(i)) continue;
            int count = 1;
            set.remove(i);
            int prev = i-1;
            int next = i+1;
            while(set.contains(prev)){
                count++;
                set.remove(prev);
                prev--;
            }
            while(set.contains(next)){
                count++;
                set.remove(next);
                next++;
            }
            result = Math.max(result, count);
        }
        return result;
    }

 

posted on 2018-09-07 10:37  葫芦胡同749  阅读(70)  评论(0编辑  收藏  举报

导航