Longest Consecutive Sequence

本文深入探讨了如何在未排序整数数组中寻找最长连续元素序列的问题,通过使用哈希映射实现高效查找,避免了传统并查集的复杂合并过程,确保算法运行在O(n)的时间复杂度内。

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

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

这是一道拿在手上不知道怎么下手的题目,题目tag提示是并查集,但是感觉和传统的并查集合并思路差别很大.参考了discussion里面的一个解决思路,主要是应用hashmap记录每个元素所属连续区间的长度,每次更新现有区间的两边节点的value为当前序列的长度.代码如下:

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #how to use the union-find how to union
        #smallest,largest element 
        hash = {}
        res = 0
        for i in nums:
            if i not in hash: #防止重复
                left = hash[i-1] if i-1 in hash else 0 #获取左边部分的长度
                right = hash[i+1] if i+1 in hash else 0 #获取右边部分的长度
                total = left + right + 1
                hash[i] = total
                res = max(res, total)  #更新最长长度
                hash[i-left] = total   #更新边缘点的长度,非常关键,方便之后的合并
                hash[i + right] = total  #更新边缘点的长度,非常关键,方便之后的合并
        return res

 

转载于:https://www.cnblogs.com/sherylwang/p/5830171.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值