作者sustainer123 (caster )
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Wed Mar 6 17:05:39 2024
141. Linked List Cycle
確認linked list是否循環
思路:
快慢指針end
Python Code:
# 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 = head
fast = head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
今天75刷比較快 行有餘力寫一下每日 還好只是ez
快速解決
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.140.94 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1709715942.A.E97.html
推 DJYOSHITAKA: 大師 03/06 17:06
推 JIWP: 大師,剩我是廢物了 03/06 17:06
→ sustainer123: 你們是專解hard的大師 03/06 17:07
→ Rushia: 怎不寫成 while fast and fast.next: 03/06 17:07
推 MurasakiSion: 大師 03/06 17:07
→ sustainer123: 對欸 感謝建議 03/06 17:09
推 oin1104: 靠北 這我直接把裡面值改掉 然後看有沒有重複走到 03/06 17:13
→ sustainer123: 靠 給code 還能改值喔 我完全沒想到這招 03/06 17:15
→ sustainer123: 不過改值的速度不快吧? 03/06 17:15
推 oin1104: 比較慢 可是我一開始沒想那麼多就做了 看解答才找到可以 03/06 17:17
→ oin1104: 快滿指針 03/06 17:17
→ sustainer123: 我是直覺就快慢指針 75有類似題目 上個月才寫過 03/06 17:19