[リートコード] 0128. 最長連続シーケンス

Python、C++、JavaScript、SQL、TypeScript の多様な LeetCode ソリューションを探索してください。面接の準備、学習、複数のプログラミング言語でのコードの練習に最適です。 Github リポジトリ リンク

中くらい

 


Given an unsorted array of integers 数字、 戻る the length of the longest consecutive elements sequence.

で実行されるアルゴリズムを作成する必要があります。 の上) time.

例 1:

入力: nums = [100,4,200,1,3,2]
出力: 4
説明: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

例 2:

入力: nums = [0,3,7,2,5,8,4,6,0,1]
出力: 9

制約:

  • 0 <= nums.length <= 105
  • -10 9 <= nums[i] <= 10 9

パイソン

				
					from typing import List


class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        longestStreak = 0
        numSet = set(nums)

        for num in nums:
            if num - 1 not in numSet:
                currentNum = num
                currentStreak = 1

                while currentNum + 1 in numSet:
                    currentNum += 1
                    currentStreak += 1

                longestStreak = max(longestStreak, currentStreak)

        return longestStreak
				
			
ja日本語