哈希-02-最长连续序列

文章目录

  • [1. 题目描述](#1. 题目描述)
  • [2. 思路](#2. 思路)
  • [3. 代码](#3. 代码)

1. 题目描述

给定一个未排序的整数数组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

示例 3:

输入:nums = 1,0,1,2

输出:3

提示:

  • 0 <= nums.length <= 10^5
  • -10^9 <= numsi <= 10^9

2. 思路

  • 不考虑时间复杂度解法:
    • 对数组排序,按照指针法持续比较相邻两位数字的大小,是否满足nums[j-1] + 1 == nums[j]
    • 考虑数组长度为0和1的边界情况。
  • O(n)解法:
    • 结合示例3和题干要求------不要求序列元素在原数组中连续,那么只要存在连续的数字就可以了,可以对数组去重(结合set的特性)。
    • 找到连续序列的起点(判断set中是否有比当前数字更小的),如果没有可以确定是起点。
    • 后续持续判断是否存在比当前数字大1的,有就更新长度。

3. 代码

  • 不考虑时间复杂度:
java 复制代码
public int longestConsecutive(int[] nums) {
    ArrayList<Integer> lens = new ArrayList<>();
    Arrays.sort(nums);

    if (nums.length == 1) {
      return 1;
    }

    for (int i = 0; i < nums.length; i++) {
      int count = 1;
      for (int j = i+1; j < nums.length; j++) {
        if (nums[j-1] + 1 == nums[j]) {
          count ++;
        } else if (nums[j] == nums[j-1]) {
          if (j == nums.length-1) {
            lens.add(count);
          }
          continue;
        } else {
          lens.add(count);
          break;
        }
        if (j == nums.length-1) {
          lens.add(count);
        }
      }
    }
    Collections.sort(lens);


    return lens.isEmpty() ? 0:lens.get(lens.size()-1);
  }
  • O(n)解法:
java 复制代码
public int longestConsecutive2(int[] nums) {
    if (nums == null || nums.length == 0) {
      return 0;
    }
    Set<Integer> numSet = new HashSet<>();
    for (int num : nums) {
      numSet.add(num);
    }

    int len = 0;
    for (Integer num : numSet) {
      if (!numSet.contains(num-1)) {
        //可以确定为起点
        int currentNum = num;
        int currentLen = 1;
        while (numSet.contains(currentNum + 1)) {
          currentLen ++;
          currentNum ++;
        }
        len =  Math.max(len, currentLen);
      }
    }
    return len;
  }

以上为个人学习分享,如有问题,欢迎指出:)

相关推荐
爱刷碗的苏泓舒1 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
烬羽4 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
闪电悠米4 小时前
力扣hot100-41.缺失的第一个正数-原地哈希详解
数据结构·算法·哈希算法
星空露珠5 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
QXWZ_IA7 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
Kel7 小时前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构
陕西企来客7 小时前
2026年7月技术好GEO优化方案:算法适配与内容策略
人工智能·算法·机器学习·技术好geo优化
风栖柳白杨7 小时前
【面试】AI算法工程师_空白自测版本
人工智能·算法·面试
闪电悠米8 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
栋***t9 小时前
从“纸质试卷”到“AI智能组卷”,麦塔在线考试系统如何重构出题逻辑?
java·大数据·人工智能·算法·重构