leetcode 128 最长连续序列

87 阅读1分钟

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

思路:这道题一般人一看见就会想到使用排序,然后遍历一次就可以解决,这样的解法也是可行的,但是题目进阶要求需要O(n)的时间复杂度时候,这种解法就不符合题意。因为你即使使用java自带的Array的sort方法,仍然是nlogn的复杂度,更不用说如果自己使用冒泡排序、插入排序等低级排序方法。

解决办法:首先就直接将所有的数组元素放入hashset中,进行去重。然后利用for增强型循环依次遍历每一个set集合中的元素(i),当不包含i-1时,就进行对其保留,再使用一个while循环进行累加,判断集合中是否存在,最后就是一个比较原来的最大值与现在的最大值即可。

空间复杂度为set集合的容量O(n),时间复杂度为外层循环的枚举O(1)乘以内层循环O(n)为O(n)

代码如下:

public int longestConsecutive(int[] nums) {
    Set<Integer> set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    int res = 0;
    for (Integer i : set) {
        if (!set.contains(i-1)){
            int currentRes = 1;
            int currentNum = i;
            while (set.contains(currentNum+1)){
                currentRes += 1;
                currentNum += 1;
            }
            res = Math.max(currentRes,res);
        }
    }
    return res;
}