from collections import defaultdict
# 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:
if head:
visited = defaultdict(list)
thisNode = head
visited[thisNode.val].append(thisNode)
while thisNode.next:
nextNode = thisNode.next
if nextNode.val in visited:
for visitedValNode in visited[nextNode.val]:
if visitedValNode is nextNode:
# address compare
return True
visited[nextNode.val].append(nextNode)
thisNode = nextNode
return False
너무 느리다 너무 느려
개선이 필요하다
# 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:
if head:
visited = set()
thisNode = head
visited.add(id(thisNode))
while thisNode.next:
nextNode = thisNode.next
if id(nextNode) in visited:
return True
visited.add(id(nextNode))
thisNode = nextNode
return False
여전히 그닥 빠르진 않다;;;;
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if head:
visited = dict()
thisNode = head
visited[id(thisNode)] = True
while thisNode.next:
nextNode = thisNode.next
if id(nextNode) in visited:
return True
visited[id(nextNode)] = True
thisNode = nextNode
return False
무조건적으로 dict가 set보다 빠른건 또 아닌가보다...
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if head:
visited = set()
thisNode = head
visited.add(hash(thisNode))
while thisNode.next:
if hash(thisNode.next) in visited:
return True
thisNode = thisNode.next
visited.add(hash(thisNode))
return False
hash()
는 python의 내장함수