Skip to content

Commit cd3d89e

Browse files
committed
Linked List Cycle
1 parent a0c0815 commit cd3d89e

File tree

2 files changed

+41
-17
lines changed

2 files changed

+41
-17
lines changed

โ€Žlinked-list-cycle/socow.pyโ€Ž

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
๐Ÿ“š 141. Linked List Cycle
3+
4+
๐Ÿ“Œ ๋ฌธ์ œ ์š”์•ฝ
5+
- ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์— ์‚ฌ์ดํด(์ˆœํ™˜)์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ
6+
- ์žˆ์œผ๋ฉด True, ์—†์œผ๋ฉด False
7+
8+
๐ŸŽฏ ํ•ต์‹ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜
9+
- ํŒจํ„ด: ํ”Œ๋กœ์ด๋“œ ์ˆœํ™˜ ํƒ์ง€ (ํ† ๋ผ์™€ ๊ฑฐ๋ถ์ด)
10+
- ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
11+
- ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
12+
13+
๐Ÿ’ก ํ•ต์‹ฌ ์•„์ด๋””์–ด
14+
1. slow๋Š” ํ•œ ์นธ์”ฉ, fast๋Š” ๋‘ ์นธ์”ฉ ์ด๋™
15+
2. ์‚ฌ์ดํด์ด ์žˆ์œผ๋ฉด โ†’ ๋‘˜์ด ์–ธ์  ๊ฐ€ ๋งŒ๋‚จ!
16+
3. ์‚ฌ์ดํด์ด ์—†์œผ๋ฉด โ†’ fast๊ฐ€ ๋์— ๋„๋‹ฌ (None)
17+
"""
18+
19+
from typing import Optional
20+
21+
22+
class ListNode:
23+
def __init__(self, val=0, next=None):
24+
self.val = val
25+
self.next = next
26+
27+
28+
class Solution:
29+
def hasCycle(self, head: Optional[ListNode]) -> bool:
30+
slow = head
31+
fast = head
32+
33+
while fast and fast.next:
34+
slow = slow.next # ๊ฑฐ๋ถ์ด: ํ•œ ์นธ
35+
fast = fast.next.next # ํ† ๋ผ: ๋‘ ์นธ
36+
37+
if slow == fast: # ๋งŒ๋‚ฌ๋‹ค!
38+
return True
39+
40+
return False # fast๊ฐ€ ๋์— ๋„๋‹ฌ = ์‚ฌ์ดํด ์—†์Œ
41+

โ€Žlongest-substring-without-repeating-characters/socow.pyโ€Ž

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,4 @@ def lengthOfLongestSubstring(self, s: str) -> int:
3535
return max_len
3636

3737

38-
# Set์„ ์‚ฌ์šฉํ•œ ๋ฐฉ์‹ (๋” ์ง๊ด€์ )
39-
class SolutionWithSet:
40-
def lengthOfLongestSubstring(self, s: str) -> int:
41-
char_set = set()
42-
left = 0
43-
max_len = 0
44-
45-
for right in range(len(s)):
46-
# ์ค‘๋ณต์ด ์‚ฌ๋ผ์งˆ ๋•Œ๊นŒ์ง€ left ์ด๋™
47-
while s[right] in char_set:
48-
char_set.remove(s[left])
49-
left += 1
50-
51-
char_set.add(s[right])
52-
max_len = max(max_len, right - left + 1)
53-
54-
return max_len
5538

0 commit comments

Comments
ย (0)