---
# System prepended metadata

title: Leetcode 128. Longest Consecutive Sequence

---

# Leetcode 128. Longest Consecutive Sequence

## 題解

### 使用 HashSet

把 Array 轉換成 HashSet，依序檢查每個數字，每次查看數字是否為開始的數字，如果是，則開始檢查連續遞增序列，並每次更新最大序列組合。

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

        for num in nums_set:
            if num - 1 not in nums_set:
                cn = num
                ans = 1
                while cn + 1 in nums_set:
                    cn = cn + 1
                    ans += 1
                output = max(output,ans)
        
        return output
```