leetcode-最长连续序列

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

-109 <= nums[i] <= 109

  1. 思路一:首先排个序,然后双指针思路。当前的数减去前一个数等于一,temp++。相等就继续。不相等就更新结果,temp重新赋值为1。

  2. 思路二:将所有的值加入到set中,去重。然后遍历set元素,判断当前元素是否为第一个开头的元素(num-1是否在集合中),为开头,从当前元素值开始加一,直到值不在set中。

  3. 思路三:直接使用TreeSet。将所有元素值加入TreeSet中,遍历,取出当前值,当前值和前一个值相差为一,temp++,不为1,更新结果。

c 复制代码
class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums.length==0)return 0;
        if(nums.length==1)return 1;
        Arrays.sort(nums);
        int start = 0;
        int maxLen = 0;
        int i = 0;
        int temp = 1;
        for(i = 0;i<nums.length;i++){
            if(i==0){
                continue;
            }else if(nums[i]-nums[i-1]==1){
                temp++;
            }else if(nums[i]!=nums[i-1]){
                maxLen = Math.max(maxLen, temp);
                temp = 1;
            }
        }
        return Math.max(maxLen,temp);
    }
}
c 复制代码
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> s = new HashSet<>();
        for(int i = 0; i < nums.length; i++){
            s.add(nums[i]);
        }
        int maxLen = 0;
        for(int x:s){
        	// 当前元素为一个序列的开头元素
            if(!s.contains(x-1)){
                int t = x+1;
                // 值加一判断是否在集合中
                while(s.contains(t)){
                    t++;
                }
                // 更新结果
                maxLen = Math.max(maxLen, t-x);
            }
        }
        return maxLen;
    }
}
c 复制代码
class Solution {
    public int longestConsecutive(int[] nums) {
        TreeSet<Integer> treeSet = new TreeSet<>();
        for(int i = 0;i<nums.length;i++){
            treeSet.add(nums[i]);
        }
        int temp = 0;
        Integer pre = Integer.MIN_VALUE;
        Integer maxLen = 0;
        for(Integer x:treeSet){
            if(x-pre==1){
                temp++;
            }else{
                maxLen = Math.max(maxLen, temp);
                temp = 1;
            }
            pre = x;
        }
        return Math.max(maxLen,temp);
    }
}
相关推荐
jerryinwuhan1 天前
hello算法,简单讲(1)
算法·排序算法
y = xⁿ1 天前
20天速通LeetCodeday15:BFS广度优先搜索
算法·宽度优先
目黑live +wacyltd1 天前
算法备案:常见驳回原因与应对策略
人工智能·算法
磊 子1 天前
多态类原理+四种类型转换+异常处理
开发语言·c++·算法
染指11101 天前
3.AI大模型-token是什么-大模型底层运行机制
人工智能·算法·机器学习
谙弆悕博士1 天前
快速学C语言——第19章:C语言常用开发库
c语言·开发语言·算法·业界资讯·常用函数
光影少年1 天前
前端算法题
前端·javascript·算法
南宫萧幕1 天前
基于 Simulink 与 Python 联合仿真的 eVTOL 强化学习全链路实战
开发语言·人工智能·python·算法·机器学习·控制
电魂泡哥1 天前
CMS垃圾回收
java·jvm·算法