【算法训练】LeetCode#128 最长连续序列

一、描述

128. 最长连续序列

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

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

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

示例 2:

输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9

二、思路

这里所说的 ‘ 数字连续 ’,不举一个特殊例子容易写错....比如[0,1,1,2],此时最长为3,因为0,1,2.....

  • v1:这个版本就是遍历并排序,虽然用到了set,但只是简单的去重,时间复杂度不符合题意。
  • v2:利用set去重后,从当前位置向+1方向找寻元素并更新长度。

三、解题


public class LeetCode128 {

    public static int longestConsecutiveV1(int[] nums) {
        if (nums == null || nums.length < 1){
            return 0;
        }
        HashSet<Integer> set = new HashSet<>();
        for (int val : nums){
            if (!set.contains(val)){
                set.add(val);
            }
        }
        PriorityQueue<Integer> arr = new PriorityQueue<>();
        for (int val : set){
            arr.add(val);
        }
        int n = nums.length;
        int ans = 1;
        int len = 1;
        int last = arr.poll();
        while (arr.size() > 0){
            int cur = arr.poll();
            if (cur - last != 1){
                // 不连续
                len = 1;
            } else {
                // 连续
                len++;
            }
            last = cur;
            ans = Math.max(ans,len);
        }
        return ans;
    }


    public static int longestConsecutiveV2(int[] nums) {
        if (nums == null || nums.length < 1){
            return 0;
        }
        HashSet<Integer> set = new HashSet<>();
        for (int val : nums){
            set.add(val);
        }
        int n = nums.length;
        int ans = 0;
        for (int curVal : set){
            if (!set.contains(curVal-1)){
                // 如果curVal-1不存在,则将当前位置作为起点向右找寻连续序列
                int curNum = curVal;
                int curLen = 1;
                while (set.contains(curNum+1)){
                    // 存在则继续
                    curNum++;
                    curLen++;
                }
                ans = Math.max(curLen,ans);
            }
        }
        return ans;
    }
}

posted @ 2023-02-13 17:01  小拳头呀  阅读(7)  评论(0编辑  收藏  举报