Unionfind----128. Longest Consecutive Sequence

原题目

参考

显然是不能使用比较排序的,然后还要设计到去重的问题,于是使用set了,于是想到使用TreeSet,一键解决美滋滋,不过比较恼人的是不能进行索引遍历,所以还得先复制到一个数组里去

 public int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        Set<Integer> set = new TreeSet<>();
        for (int i = 0; i < nums.length; i++) {
            set.add(nums[i]);
        }
        int[] arrays = new int[nums.length];
        int k = 0;
        for (Integer i : set) {
            arrays[k++] = i;
        }

        int max = 0;
        int result = 0;
        for (int i = 0; i < arrays.length - 1; i++) {

            if (arrays[i] + 1 == arrays[i + 1]) {
                result++;
            } else {
                if (result + 1 > max) {
                    max = result + 1;
                }
                result = 0;
            }
        }
        //假如在i超出范围的时候没有进行操作就是不行的。所以最后有可能还剩一个没有比较的result。
        max = Math.max(max, result + 1);
        return max;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值