力扣第128题最长的连续序列

128.最长连续序列
难度:困难
标签:并查集

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

要求算法的时间复杂度为 O(n)。
示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

思路:运用并查集,使用hashmap fatherset key是数组的值,value是key的父结点
初始化时,一共n个树。还有一个hashmap size 放的是每棵树的大小结点个数
遍历数组,然后把判断nums[i]-1是否在 fatherset中 在的话,合并两个结点,合并的时候,需要更新最大的树的结点个数

public int longestConsecutive(int[] nums){
    if(nums==null||nums.length==0)
        return 0;
    UF uf=new UF(nums);
    for (int i = 0; i < nums.length; i++) {
        if(uf.fatherset.containsKey(nums[i]-1)){
            uf.union(nums[i],nums[i]-1);
        }
    }
    return uf.max;
}
class UF{
    public int max=1;
    private int count;
    public HashMap<Integer,Integer> fatherset=new HashMap<>();
    public HashMap<Integer,Integer> size=new HashMap<>();
    public UF(int[] nums){
        for(int i=0;i<nums.length;i++){
            fatherset.put(nums[i],nums[i]);
            size.put(nums[i],1);
        }
        count=nums.length;
    }
    public int find(int p){
        int father=fatherset.get(p);
        if(p!=father) {
            father=find(father);
            fatherset.replace(p,father);
        }
        return father;
    }
    public void union(int p,int q){
        int proot=find(p);
        int qroot=find(q);
        if(proot==qroot) return;
        if(size.get(proot)<size.get(qroot)){
            fatherset.replace(proot,qroot);
            size.replace(qroot,size.get(qroot)+size.get(proot));
            max=Math.max(max,size.get(qroot));
        }
        else {
            fatherset.replace(qroot,proot);
            size.replace(proot,size.get(qroot)+size.get(proot));
            max=Math.max(max,size.get(proot));
        }
        count--;
    }

准备一个hashset,将所有的num放入到里面
遍历时,只有当num-1不在set里面时,说明出现了新的序列
就寻找这个序列的长度,然后更新最大的长度

public int longestConsecutive(int[] nums) {
    Set<Integer> num_set = new HashSet<Integer>();
    for (int num : nums) {
        num_set.add(num);
    }

    int longestStreak = 0;

    for (int num : num_set) {
        if (!num_set.contains(num-1)) {
            int currentNum = num;
            int currentStreak = 1;

            while (num_set.contains(currentNum+1)) {
                currentNum += 1;
                currentStreak += 1;
            }

            longestStreak = Math.max(longestStreak, currentStreak);
        }
    }

    return longestStreak;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值