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 <= numsi <= 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);
    }
}
相关推荐
退休倒计时6 小时前
【每日一题】LeetCode 19. 删除链表的倒数第 N 个结点 TypeScript
leetcode·链表·typescript
装不满的克莱因瓶7 小时前
掌握生成对抗网络(GAN)的优化目标与评估指标——从博弈函数到生成质量衡量体系
人工智能·python·深度学习·算法·机器学习
技术小黑7 小时前
CNN算法实战系列06 | InceptionV1实现猴痘病识别
深度学习·算法·cnn·inceptionv1
qq_297574677 小时前
设计模式系列文章(基础篇第22篇):访问者模式——分离数据结构与操作,实现灵活扩展
数据结构·设计模式·访问者模式
云淡风轻~窗明几净7 小时前
角谷猜想的任意算法测试
数据结构·人工智能·算法
代码中介商7 小时前
关键路径解析:项目管理的工期奥秘
数据结构
happygrilclh7 小时前
赚外快了:等离子表面处理机电源算法需求说明
算法
ji198594438 小时前
MATLAB 求散点曲线斜率
开发语言·算法·matlab
kaikaile19958 小时前
MATLAB 实现:Koch & Zhao 图像水印算法(DCT域)
开发语言·算法·matlab
love_muming8 小时前
链表每日一练
java·开发语言·数据结构·链表·idea·每日一练