From cd3d89ee64c06dcc999b6392d8c1db072d55475e Mon Sep 17 00:00:00 2001 From: socow Date: Tue, 6 Jan 2026 18:05:33 +0900 Subject: [PATCH] Linked List Cycle --- linked-list-cycle/socow.py | 41 +++++++++++++++++++ .../socow.py | 17 -------- 2 files changed, 41 insertions(+), 17 deletions(-) create mode 100644 linked-list-cycle/socow.py diff --git a/linked-list-cycle/socow.py b/linked-list-cycle/socow.py new file mode 100644 index 0000000000..7a02e4c882 --- /dev/null +++ b/linked-list-cycle/socow.py @@ -0,0 +1,41 @@ +""" +๐Ÿ“š 141. Linked List Cycle + +๐Ÿ“Œ ๋ฌธ์ œ ์š”์•ฝ +- ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์— ์‚ฌ์ดํด(์ˆœํ™˜)์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ +- ์žˆ์œผ๋ฉด True, ์—†์œผ๋ฉด False + +๐ŸŽฏ ํ•ต์‹ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ +- ํŒจํ„ด: ํ”Œ๋กœ์ด๋“œ ์ˆœํ™˜ ํƒ์ง€ (ํ† ๋ผ์™€ ๊ฑฐ๋ถ์ด) +- ์‹œ๊ฐ„๋ณต์žก๋„: O(n) +- ๊ณต๊ฐ„๋ณต์žก๋„: O(1) + +๐Ÿ’ก ํ•ต์‹ฌ ์•„์ด๋””์–ด +1. slow๋Š” ํ•œ ์นธ์”ฉ, fast๋Š” ๋‘ ์นธ์”ฉ ์ด๋™ +2. ์‚ฌ์ดํด์ด ์žˆ์œผ๋ฉด โ†’ ๋‘˜์ด ์–ธ์  ๊ฐ€ ๋งŒ๋‚จ! +3. ์‚ฌ์ดํด์ด ์—†์œผ๋ฉด โ†’ fast๊ฐ€ ๋์— ๋„๋‹ฌ (None) +""" + +from typing import Optional + + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def hasCycle(self, head: Optional[ListNode]) -> bool: + slow = head + fast = head + + while fast and fast.next: + slow = slow.next # ๊ฑฐ๋ถ์ด: ํ•œ ์นธ + fast = fast.next.next # ํ† ๋ผ: ๋‘ ์นธ + + if slow == fast: # ๋งŒ๋‚ฌ๋‹ค! + return True + + return False # fast๊ฐ€ ๋์— ๋„๋‹ฌ = ์‚ฌ์ดํด ์—†์Œ + diff --git a/longest-substring-without-repeating-characters/socow.py b/longest-substring-without-repeating-characters/socow.py index 91baa03a38..63b8887f16 100644 --- a/longest-substring-without-repeating-characters/socow.py +++ b/longest-substring-without-repeating-characters/socow.py @@ -35,21 +35,4 @@ def lengthOfLongestSubstring(self, s: str) -> int: return max_len -# Set์„ ์‚ฌ์šฉํ•œ ๋ฐฉ์‹ (๋” ์ง๊ด€์ ) -class SolutionWithSet: - def lengthOfLongestSubstring(self, s: str) -> int: - char_set = set() - left = 0 - max_len = 0 - - for right in range(len(s)): - # ์ค‘๋ณต์ด ์‚ฌ๋ผ์งˆ ๋•Œ๊นŒ์ง€ left ์ด๋™ - while s[right] in char_set: - char_set.remove(s[left]) - left += 1 - - char_set.add(s[right]) - max_len = max(max_len, right - left + 1) - - return max_len