128. Longest Consecutive Sequence

本文介绍了一种在未排序整数数组中寻找最长连续元素子序列的算法,该算法的时间复杂度为O(n),并详细解释了如何使用哈希映射存储数字及其子序列长度,以高效地更新和查找子序列。

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

Description

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.

Problem URL


Solution

给一个未排序数组,找到最长的连续子集的长度。要求常数时间。

Using a map to store number and its subsequence’s length. For nums not in map, get its left neighbor and right neighbor’s subsequence length. Update it to res and map and its edge, because they are in the same subsequence. We must keep head and tail element have right updated length value.

If this num is in map, just continue. Of course, it is optional.

Code
class Solution {
    public int longestConsecutive(int[] nums) {
        int res = 0;
        //a map from num to its subsequence's length.
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums){
            if (!map.containsKey(i)){
                //get neighbors subsequence's length if exist.
                int left = map.containsKey(i - 1) ? map.get(i - 1) : 0;
                int right = map.containsKey(i + 1) ? map.get(i + 1) : 0;
                //calcualte new list length, if no neighobrs, 1;
                int sum = left + right + 1;
                res = Math.max(res, sum);
                //put new list length into map, update other edge's length value
                map.put(i, sum);
                map.put(i - left, sum);
                map.put(i + right, sum);
            }
            else{
                //duplicate circumstance;
                continue;
            } 
        }
        return res;
    }
}

Time Complexity: O(n)
Space Complexity: O(n)


Review
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值