one line of code at a time
[leetcode] 141. Linked List Cycle 파이썬 코드 본문
https://leetcode.com/problems/linked-list-cycle/
class Solution(object):
def hasCycle(self, head):
if not head:
return False
visitSet = set()
while head.next:
visitSet.add(head)
if head.next in visitSet:
return True
head = head.next
return False
방문 배열을 만들어서 연결 리스트에서 방문한 노드를 저장한다.
다음 노드가 있을 때까지 반복하는데 그 다음 노드가 방문 배열에 있다면, 사이클이 만들어진다는 의미이므로 True를 반환한다.
그리고 다음 노드로 이동한다.
만약 반복문을 끝까지 돌았는데 True가 리턴되지 않았다면, 사이클이 발견되지 않았다는 뜻이므로 False를 리턴한다.

'leetcode' 카테고리의 다른 글
| [leetcode] 386. Lexicographical Numbers 파이썬 코드 (0) | 2024.09.25 |
|---|---|
| [leetcode] 3043. Find the Length of the Longest Common Prefix 파이썬 코드 (0) | 2024.09.25 |
| [leetcode] 841. Keys and Rooms 파이썬 코드 (0) | 2024.09.24 |
| [leetcode] 17. Letter Combinations of a Phone Number 파이썬 코드 (0) | 2024.09.24 |
| [leetcode] 463. Island Perimeter 파이썬 코드 (0) | 2024.09.24 |