141. Linked List Cycle

Doyeon Kim·2022년 4월 13일

코딩테스트 공부

목록 보기
52/171

문제 링크 : https://leetcode.com/problems/linked-list-cycle/


사이클인..? 링크드 리스드면 True를 반환하는 문제이다.
그뭐냐

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow, fast = head, head
        
        while fast and fast.next :
            slow = slow.next
            fast = fast.next.next
            if slow == fast :
                return True
            
        return False
        

만약에 노드가 cycled이라면 앞에 먼저 fast가 순환하고 그 뒤에 slow가 순환할 때 둘이 같아지게..? 된다

Runtime: 61 ms, faster than 78.02% of Python3 online submissions for Linked List Cycle.
Memory Usage: 17.7 MB, less than 31.88% of Python3 online submissions for Linked List Cycle.

참고 : https://www.youtube.com/watch?v=gBTe7lFR3vc

profile
성장하고 도전하는 개발자. 프로그래밍 좋아하세요?

0개의 댓글