刷题笔记 Hot100 128. 最长连续序列

对这一题,最直截了当的想法就是,先将数组排序好,然后根绝 a[i - 1] + 1 == a[i] 的关系判断最长的连续序列
class Solution {
    public int longestConsecutive(int[] nums) {
        int max = 0, index = 1, length = nums.length;
        if (length == 0) return 0;
        // 这里使用优先队列进行排序
        PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        // 通过set去重
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < length; i++) {
            if (!set.contains(nums[i])) {
                set.add(nums[i]);
                pq.offer(nums[i]);
            }
        }
        int anchor = pq.poll();
        while (!pq.isEmpty()) {
            int num = pq.poll();
            if (anchor + 1 == num) {
                index++;
            } else {
                max = Math.max(max, index);
                index = 1;
            }
            anchor = num;
        }
        max = Math.max(max, index);
        return max;
    }
}

然而,在本题中,要求时间复杂度为0(n)级别,所以必须要想一个办法,只要遍历一次数组,就可以得出答案,这里我们想到,上面的代码中使用了set,既然有set,完全可以借助set来实现a[i - 1] + 1 == a[i]的比较。这里使用TreeSet,同时完成去重和排序的任务

class Solution {
    public int longestConsecutive(int[] nums) {
        int max = 0, index = 1, length = nums.length;
        if (length == 0) return 0;
        TreeSet<Integer> set = new TreeSet<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        for (int i = 0; i < length; i++) {
            set.add(nums[i]);
        }
        Iterator<Integer> iterator = set.iterator();
        // 获得第一个值
        int anchor = iterator.next();
        while (iterator.hasNext()) {
            int num = iterator.next();
            if (anchor + 1 == num) {
                index++;
            } else {
                max = Math.max(max, index);
                index = 1;
            }
            anchor = num;
        }
        max = Math.max(max, index);
        return max;
    }
}

通过上面的方式,远远降低了内存消耗

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值