Longest Consecutive Sequence--记录区间信息

本文介绍了一种在未排序整数数组中寻找最长连续元素序列的算法,该算法复杂度为O(n),并提供了两种解决方案:排序和使用哈希表。通过示例展示了算法的应用,如输入[100,4,200,1,3,2],输出为4,解释了最长连续元素序列是[1,2,3,4]。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Solution1: Sort it.

Solution2: Use hashmap to store consecutive intervals information, make sure the lowest and the highest both point to length of consecutive interval, such as [0,1,2,3,4], then (0->5, 4->5).

class Solution {
    public int longestConsecutive(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        int max = 0;
        for (int n : nums) {
            if (map.containsKey(n)) continue;
            map.put(n,1);
            int a = map.getOrDefault(n-1,0), b = map.getOrDefault(n+1,0);
            int newval = a+b+1;            
            max = Math.max(max,newval);
            if (a == 0 && b == 0) continue; //no neighbor
            map.put(n-a,newval); //update lowest
            map.put(n+b,newval); //update highest
        }
        return max;
    }
}

 

转载于:https://www.cnblogs.com/liudebo/p/9320727.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值