# 128. Longest Consecutive Sequence

[https://leetcode.com/problems/longest-consecutive-sequence/description/](https://leetcode.com/problems/longest-consecutive-sequence/description/)

## solution

* sort + hash

```python
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if not nums:
            return 0

        nums = list(set(nums))
        nums.sort()
        res = 1
        temp = 1
        for i in range(len(nums) - 1):
            if nums[i+1] == nums[i] + 1:
                temp += 1
                res = max(res, temp)
            else:
                temp = 1
        return res
```

时间复杂度：O()\
空间复杂度：O()

```python
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        nums_set = set(nums)
        res = 0

        for num in nums_set:
            # 根据前一个是否在list中判断是否已经计算过，则略过.
            if num - 1 in nums_set:
                continue

            # 寻找每一段连续的第一个数，并借此寻找其开始的连续段
            length = 1
            while num + 1 in nums_set:
                length += 1
                num += 1
            
            # 更新结果
            res = max(res, length)
        return res
```

```python
# 所有数字放到一个哈希表，然后不断地从哈希表中任意取一个值，并删除掉其之 前之后的所有连续数字，然后更新目前的最长连续序列长度

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if len(nums) < 2:
            return len(nums)

        nums_map = {}
        longest_consecutive = 0
        for num in nums:
            if num not in nums_map:
                nums_map[num] = [num, num]
                left = num
                right = num

                # left neighbor - extend left range
                if num - 1 in nums_map:
                    left = nums_map[num - 1][0]

                # right neighbor - extend right range
                if num + 1 in nums_map:
                    right = nums_map[num + 1][1]

                nums_map[left] = [left, right]
                nums_map[right] = [left, right]
                longest_consecutive = max(longest_consecutive, right - left + 1)

        return longest_consecutive
```

## follow up

* 二维数组
