LeetCode: 最长连续序列128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

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

You must write an algorithm that runs in O(n) time.

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Constraints:

0 <= nums.length <= 105
-109 <= nums[i] <= 109

用set来解决

  1. Add all nums in set
  2. Then we will run a for loop and check for any number(x) if it is the starting number of the consecutive sequence by checking if the set contains (x-1) or not
  3. If x is the starting number of the consecutive sequence we will keep searching for the numbers y = x+1, x+2, x+3, …… And stop at the first y which is not present in the set
  4. Time Complexity: O(n) (assuming set takes O(1) to search)
  5. Space Complexity: O(n)
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if len(nums) == 0: return 0
        uset = set(nums)
        maxi = 1
        for i in uset:
            if i-1 in uset:
                continue
            else:
                conseq = 1
                while i + conseq in uset:
                    conseq += 1
                maxi = max(maxi, conseq)
        return maxi

猜你喜欢

转载自blog.csdn.net/zgpeace/article/details/131273955