python中的字典是基于哈希表实现的,因此本题我们可以利用python中的字典来解决:
如果有环的话,一些数据肯定会重复出现,因此一旦出现重复数字,就可判断有环。
class Solution:
def hasCycle(self, head: ListNode) -> bool:
num = set()
while head:
if head in num:
return True
num.add(head)
head = head.next
return False
上一题还有个进阶版,如果有环,则返回环的入口,详见142. 环形链表 II
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
num = set()
while head:
if head in num:
return head
num.add(head)
head = head.next
return None
再来一个变种的,本质也是判断有无环
这个有个细节需要注意,在python3中,9 / 10 = 0.9 ,而不是0。//在python中表示整除。
class Solution:
def isHappy(self, n: int) -> bool:
if n == 1: return True
num = set()
while n:
if n in num:
return False
num.add(n)
i = 0
while n:
i += (n % 10)**2
n = n // 10
n = i
if n == 1:return True
return True