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

一、题目

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

要求算法的时间复杂度为 O(n)

二、思路

通过将数组中的数字放入set中,然后遍历数组,查找set中是否有连续的序列

三、实现

public static int longestConsecutive(int[] nums) {
    Set<Integer> set = new HashSet<>();

    for (int num : nums) {
        set.add(num);
    }

    int res = 0;

    for (int num : nums) {
        if (!set.remove(num)) {
            continue;
        }

        int count = 1;

        int tmp = num;

        while (set.remove(--num)) {
            count += 1;
        }

        while (set.remove(++tmp)) {
            count += 1;
        }

        res = Math.max(res, count);

        if (res >= set.size()) {
            break;
        }
    }

    return res;
}
发布了83 篇原创文章 · 获赞 0 · 访问量 4529

猜你喜欢

转载自blog.csdn.net/zhangdx001/article/details/105412646