classSolution:defhasCycle(self,head: Optional[ListNode]) ->bool:if head isNoneor head.next isNone:returnFalse slow = head fast = head.nextwhile fast isnotNoneand fast.next isnotNone:if slow == fast:returnTrue slow = slow.next fast = fast.next.nextreturnFalse
时间复杂度:O(n)
空间复杂度:O(1)
follow up
SPFA 判断是否有负环
import collectionsn, m =map(int, input().split())g = collections.defaultdict(list)st = [Truefor i inrange(n+1)]dist = [0for i inrange(n+1)]cnt = [0for i inrange(n+1)]for i inrange(m): a, b, w =map(int, input().split()) g[a].append([b, w])defspfa(): q = [i for i inrange(n+1)]whilelen(q)!=0: a = q.pop()## 这里要注意 如果用pop(0) 会超时,这是因为 Python中 pop(0)复杂度O(n),pop()是O(1) st[a]=Falsefor b, w in g[a]:if dist[b]> dist[a]+ w: cnt[b]= cnt[a]+1if cnt[b]>= n:returnTrue dist[b]= dist[a]+ wif st[b]==False: q.append(b)returnFalseprint("Yes"ifspfa() else"No")