← Back to library
#128MediumArrayHash Table AIに質問leetcode ↗

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

Example 3:

Input: nums = [1,0,1,2]
Output: 3

Constraints:

  • 0 <= nums.length <= 10<sup>5</sup>
  • -10<sup>9</sup> <= nums[i] <= 10<sup>9</sup>
使用した概念Hash Table

アプローチ

思考
  • 連続値の最大を検出する
  • numsの各要素に対して、連続する値があるかroopで走査する
  • このとき、次の値の検索をO(1)で行う。
  • そのため、numsの値をhash mapで管理することで、O(1)での検索を行う。
実装
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        hash_nums = set(nums)
        max_seq = 0

        for num in nums:
            is_consequtive = True
            cur_seq = 0

            while is_consequtive:
                if num in hash_nums:
                    max_seq = max(max_seq, cur_seq + 1)
                    cur_seq += 1
                    num += 1
                else:
                    is_consequtive = False
        return max_seq
Time Space
注意点
  • Time Limit Exceededが発生する
    • すべての num から連続列を最後まで探索しているため
    • 計算量はO(n2)O(n^2)になる