每天(?)一道Leetcode(17) Longest Consecutive Sequence

Array

128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity. (要求了复杂度)
即 找出给定无序数组中最长连续子列的长度

  • 举个例子:
    Input:
    Output:

上述例子中最长连续子列是,所以返回

class Solution:
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        longest_streak = 0
        num_set = set(nums)

        for num in num_set:
            if num - 1 not in num_set:
                current_num = num
                current_streak = 1

                while current_num + 1 in num_set:
                    current_num += 1
                    current_streak += 1

                longest_streak = max(longest_streak, current_streak)

        return longest_streak

你可能感兴趣的:(每天(?)一道Leetcode(17) Longest Consecutive Sequence)