Skip to content

Commit 63956b5

Browse files
committed
feat: Solve longest-consecutive-sequence problem
1 parent 2771cad commit 63956b5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
"""
3+
nums๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ sortํ•˜๊ณ , ์ฐจ๋ก€๋Œ€๋กœ ๋‘ ๊ฐœ์˜ ์ฐจ๊ฐ€ ๋‹ค์Œ ์ฐจ๊ฐ€ ๊ฐ™๋‹ค๋ฉด + 1
4+
์ฒ˜์Œ ์ฐจ๋Š” diff ๋ณ€์ˆ˜์— ์ €์žฅํ•˜๊ณ , ์ง„ํ–‰๋˜๋ฉด์„œ diff๋ฅผ ์—…๋ฐ์ดํŠธ
5+
200, 100, 4, 3, 2, 1
6+
7+
์—ฐ์†๋œ ์ˆ˜์—ด์ด๋ผ๊ณ  ํ•˜์—ฌ 1 ์ด์™ธ์˜ ๋‹ค๋ฅธ ์ˆ˜๊ฐ€ ์˜ฌ ์ˆ˜ ์žˆ์„ ๊ฒƒ์ด๋ผ๊ณ  ํŒ๋‹จํ•˜์˜€์ง€๋งŒ ์ฐจ์ด๊ฐ€ 1๋กœ ๋‚˜์˜จ๋‹ค๋Š” ๊ฒƒ์„ ํ™•์ธ
8+
9+
- TC
10+
- set(nums) -> O(n)
11+
- for -> O(n)
12+
- while -> O(n)
13+
- ์ „์ฒด -> O(n)
14+
- SC
15+
- num_set -> O(n)
16+
- ๋‹ค๋ฅธ ๋ณ€์ˆ˜๋“ค -> O(1)
17+
- ์ „์ฒด -> O(n)
18+
"""
19+
def longestConsecutive(self, nums: List[int]) -> int:
20+
num_set = set(nums)
21+
longest = 0
22+
23+
for num in num_set:
24+
if num - 1 not in num_set:
25+
k = 1
26+
27+
while num + k in num_set:
28+
k += 1
29+
30+
longest = max(longest, k)
31+
return longest

0 commit comments

Comments
ย (0)