Lintcode 124. Longest Consecutive Sequence (Medium) (Python)

Longest Consecutive Sequence

Description:

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

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

Clarification
Your algorithm should run in O(n) complexity.

Code:

class Solution:
    """
    @param num: A list of integers
    @return: An integer
    """
    def longestConsecutive(self, num):
        # write your code here
        dic = {}
        for i in sorted(num):
            dic[i]=0
        maxLen = 1
        for i in dic:
            if dic[i]==1:
                continue
            l = 1
            dic[i] = 1
            while i+1 in dic:
                dic[i+1] = 1
                i = i+1
                l += 1
                maxLen = max(maxLen, l)
        return maxLen

你可能感兴趣的:(Lintcode刷题)