Skip to content

Commit f7ae499

Browse files
committed
Solved 128. Longest Consecutive Sequence problem
1 parent a4fa1ea commit f7ae499

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
Title: 128. Longest Consecutive Sequence
3+
Link: https://leetcode.com/problems/longest-consecutive-sequence/
4+
5+
Question:
6+
- Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
7+
- You must write an algorithm that runs in O(n) time.
8+
9+
Constraints:
10+
- 0 <= nums.length <= 10^5
11+
- -10^9 <= nums[i] <= 10^9
12+
13+
Time Complexity:
14+
- O(n log n)
15+
Space Complexity:
16+
- O(n)
17+
18+
Notes:
19+
- sorted(nums)๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด TC๊ฐ€ O(n log n)์ด ๋˜์–ด ๋ฌธ์ œ์˜ ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜์ง€ ๋ชปํ•˜์ง€๋งŒ, ์ด ๋ฐฉ๋ฒ•์ด ์ œ๊ฐ€ ์ƒ๊ฐํ•ด์„œ ํ’€ ์ˆ˜ ์žˆ๋Š” ์ตœ์„ ์ด๋ผ ์ผ๋‹จ ์ด๋Œ€๋กœ ์ œ์ถœํ•ฉ๋‹ˆ๋‹ค! ๋‹ค๋ฅธ ๋ถ„๋“ค ๋‹ต์•ˆ ์ฐธ๊ณ ํ•˜์—ฌ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค :)
20+
"""
21+
22+
class Solution:
23+
def longestConsecutive(self, nums: List[int]) -> int:
24+
nums = sorted(nums)
25+
max_length = 0
26+
current_length = 1
27+
28+
for i in range(1, len(nums)):
29+
if nums[i] == nums[i-1] + 1:
30+
current_length += 1
31+
elif nums[i] == nums[i-1]:
32+
continue
33+
else:
34+
max_length = max(max_length, current_length)
35+
current_length = 1
36+
37+
max_length = max(max_length, current_length)
38+
return max_length

0 commit comments

Comments
ย (0)