leetcode 128. Longest Consecutive Sequence 并查集

1.题目

给定一个未排序的整数数组,找出最长连续序列的长度。

2.思路

将相邻的数字union

核心是并查集的思想,用一个map来作为一个工具

 遍历给出的样例,将每个元素依次加入哈希map中,<元素的值,索引>

如果有相同元素,忽略

如果有相邻元素(比当前元素大1或小1),union两个元素的map索引值

find函数和union函数没有变化

新添加了一个计算最长长度的函数maxlength:

    具体实现是借助一个count数组(初始值为0,作用是计算每个索引的子结点数)

    从0遍历到nums-1,找出每个索引的根结点的索引,将其+1,

    最后遍历count数组,找到最大值即为最长连续序列

3.坑

如何解决负数的问题,数字太大怎么办(用map的索引值替代这些)
4.代码

class Solution {
    public int longestConsecutive(int[] nums) {
        UF uf=new UF(nums.length);
        Map<Integer,Integer> m=new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
            if(m.containsKey(nums[i]))
                continue;
            m.put(nums[i],i);
            if(m.containsKey(nums[i]+1))
                uf.union(i,m.get(nums[i]+1));
            if(m.containsKey(nums[i]-1))
                uf.union(i,m.get(nums[i]-1));
            
        }
        return uf.maxlength();
    }
    
}
class UF{
    int []id;
    public UF(int n){
        id=new int[n];
        for(int i=0;i<n;i++)
            id[i]=i;
    }
    public int find(int x){
        while(x!=id[x]){
            x=id[x];
        }
        return x;
    }
    public int connected(int p,int q){
        //这里用不上
        return 0;
    }
    public void union(int p,int q){
        int proot=find(p);
        int qroot=find(q);
        id[proot]=qroot;//id[p]=qroot
    }
    public int maxlength(){
        int maxlength=0;
        int []count=new int[id.length];
       
        for(int i=0;i<id.length;i++){
            count[find(i)]++;
            maxlength=Math.max(maxlength,count[find(i)]);
        }
        return maxlength;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值