[leetcode]Longest Consecutive Sequence @ Python

本文针对LeetCode上的一道题目——寻找整数数组中最长连续元素序列的长度,提出了一种时间复杂度为O(n)的高效解决方案。通过使用Python中的字典数据结构来记录每个元素的状态,并遍历字典找出最长连续序列。

原题地址:https://oj.leetcode.com/problems/longest-consecutive-sequence/

题意:

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.

解题思路:使用一个哈希表,在Python中是字典dict数据类型。dict中的映射关系是{x in num:False},这个表示num中的x元素没有被访问过,如果被访问过,则为True。如果x没有被访问过,检查x+1,x+2...,x-1,x-2是否在dict中,如果在dict中,就可以计数。最后可以求得最大长度。

代码:

class Solution:
    # @param num, a list of integer
    # @return an integer
    def longestConsecutive(self, num):
        dict = {x: False for x in num} # False means not visited
        maxLen = -1
        for i in dict:
            if dict[i] == False:
                curr = i+1; lenright = 0
                while curr in dict:
                    lenright += 1; dict[curr] = True; curr += 1
                curr = i-1; lenleft = 0
                while curr in dict:
                    lenleft += 1; dict[curr] = True; curr -= 1
                maxLen = max(maxLen, lenleft+1+lenright)
        return maxLen

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值