Skip to content

Commit 8897d04

Browse files
committed
feat: longestConsecutive solutions
1 parent 11a76ef commit 8897d04

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from typing import List
2+
3+
"""
4+
문제 μ„€λͺ…:
5+
μ •λ ¬λ˜μ§€ μ•Šμ€ μ •μˆ˜ λ°°μ—΄μ—μ„œ κ°€μž₯ κΈ΄ μ—°μ†λœ 숫자 μˆ˜μ—΄μ˜ 길이λ₯Ό λ°˜ν™˜ν•˜λŠ” 문제
6+
O(n) μ‹œκ°„λ³΅μž‘λ„λ‘œ ν•΄κ²°ν•΄μ•Ό 함 => μ •λ ¬ x
7+
8+
λͺ©ν‘œ:
9+
- ν•΄μ‹œ μ„ΈνŠΈλ‘œ 쀑볡 제거
10+
- 연속 μˆ˜μ—΄μ˜ μ‹œμž‘μ  μ°ΎκΈ°
11+
12+
[100,4,200,1,3,2]
13+
- ν•΄μ‹œ μ„ΈνŠΈ: {100, 4, 200, 1, 3, 2}
14+
- μ‹œμž‘μ  μ°ΎκΈ°: 1 (0이 μ—†μŒ), 100 (99κ°€ μ—†μŒ), 200 (199κ°€ μ—†μŒ)
15+
- 1μ—μ„œ μ‹œμž‘: 1β†’2β†’3β†’4 (길이 4)
16+
- 100μ—μ„œ μ‹œμž‘: 100만 (길이 1)
17+
- 200μ—μ„œ μ‹œμž‘: 200만 (길이 1)
18+
- μ΅œλŒ€ 길이: 4
19+
20+
- for num=1: 0이 μ—†μœΌλ―€λ‘œ μ‹œμž‘μ  β†’ whileμ—μ„œ 1,2,3,4 처리
21+
- for num=2: 1이 μžˆμœΌλ―€λ‘œ while μŠ€ν‚΅
22+
- for num=3: 2κ°€ μžˆμœΌλ―€λ‘œ while μŠ€ν‚΅
23+
- for num=4: 3이 μžˆμœΌλ―€λ‘œ while μŠ€ν‚΅
24+
β†’ 각 μˆ«μžκ°€ whileμ—μ„œ 1번만
25+
"""
26+
27+
"""
28+
μ‹œκ°„λ³΅μž‘λ„: O(n)
29+
- set(nums) λ³€ν™˜: O(n)
30+
- μ™ΈλΆ€ for 루프: O(n)번 μ‹€ν–‰
31+
- while 총 μ‹€ν–‰ 횟수: 전체 μ•Œκ³ λ¦¬μ¦˜μ—μ„œ 각 μˆ«μžκ°€ while μ•ˆμ—μ„œ μ΅œλŒ€ 1번만 처리됨
32+
β†’ 총 while λ‚΄λΆ€ μž‘μ—… = n번 β†’ O(n)
33+
- ν•΄μ‹œ 쑰회: O(1) Γ— 총 쑰회 횟수
34+
- 전체: O(n) + O(n) + O(n) = O(n)
35+
36+
κ³΅κ°„λ³΅μž‘λ„: O(n)
37+
- num_set: μ΅œλŒ€ n개의 μ„œλ‘œ λ‹€λ₯Έ 숫자 μ €μž₯ -> O(n)
38+
- 기타 λ³€μˆ˜λ“€: O(1)
39+
- 전체: O(n)
40+
"""
41+
42+
class Solution:
43+
def longestConsecutive(self, nums: List[int]) -> int:
44+
num_set = set(nums)
45+
max_length = 0
46+
47+
48+
for num in num_set:
49+
50+
# 루프 μ•ˆμ—μ„œ ν•œλ²ˆλ§Œ 처리
51+
if num - 1 not in num_set:
52+
current_length = 1
53+
54+
while num + current_length in num_set:
55+
current_length += 1
56+
57+
max_length = max(max_length, current_length)
58+
59+
60+
return max_length
61+
62+
print(Solution().longestConsecutive([100, 4, 200, 1, 3, 2]))
63+

0 commit comments

Comments
Β (0)