leetcode #128Longest Consecutive Sequence

#128

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.
class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = 0       
        nums = set(nums)
        for num in nums:
            if num-1 not in nums:
                cn = num
                cs = 1
                while cn+1 in nums:
                    cn += 1
                    cs += 1
                ans = max(ans,cs)
        return ans


猜你喜欢

转载自blog.csdn.net/qq_36974075/article/details/80193184