Skip to content

Commit 0c700f0

Browse files
committed
Longest Consecutive Sequence Solution
1 parent 3d40dbc commit 0c700f0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# 배열을 정렬하고 포인터를 두개 사용
2+
class Solution:
3+
def longestConsecutive(self, nums: List[int]) -> int:
4+
if not nums:
5+
return 0
6+
7+
# sort the given list
8+
sorted_nums = sorted(nums)
9+
10+
longest = 1
11+
curr = 1
12+
13+
l, r = 0, 1
14+
15+
while r < len(sorted_nums):
16+
# case 1: exactly consecutive (x, x+1)
17+
if sorted_nums[r] == sorted_nums[l] + 1:
18+
curr += 1
19+
longest = max(longest, curr)
20+
l += 1
21+
r += 1
22+
23+
# case 2: duplicate (x, x) → ignore, move right pointer
24+
elif sorted_nums[r] == sorted_nums[l]:
25+
l += 1
26+
r += 1
27+
28+
# case 3: gap
29+
else:
30+
curr = 1
31+
l = r
32+
r += 1
33+
34+
return longest

0 commit comments

Comments
 (0)