반응형
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 <= 105
-109 <= nums[i] <= 109
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
num_set = set(nums)
res = 0
for n in num_set :
if n - 1 not in num_set :
length = 1
while n + length in num_set :
length += 1
res = max(res, length)
return res
해당 배열 안에 연속된 숫자가 존재하는지에 대해서 set 으로 바꾸면 중복되는 숫자를 없앨 수 있다. set안에 있는 숫자를 for문을 돌면서 연속된 숫자가 몇개가 존재하는지 카운팅한다.
for문 안에 if문은 처음 시작하는 부분을 찾는 방식이고, 이전 부분이 존재하지 않으면 1로 초기화, 아니면 while 문으로 이동한다.
while 은 n + 1, n + 2, ... , n + length 가 되므로, 최종 length 는 res 에서 가장 긴 length 를 저장한다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
[Leetcode/파이썬] 34. Find First and Last Position of Element in Sorted Array (0) | 2025.05.18 |
---|---|
[Leetcode/파이썬] 383. Ransom Note (0) | 2025.05.18 |
[Leetcode/파이썬] 172. Factorial Trailing Zeroes (0) | 2025.05.11 |
[Leetcode/파이썬] 66. Plus One (0) | 2025.05.11 |
[Leetcode/파이썬] 17. Letter Combinations of a Phone Number (0) | 2025.04.30 |