iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 52

[Day 52] Linked List Cycle (Easy)

  • 分享至 

  • xImage
  •  

141. Linked List Cycle

Solution 1: Hash

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if not head:
            return False
        
        isVisited = {}
        while head:
            if head in isVisited:
                return True
            else:
                isVisited[head] = True
            head = head.next
        return False

Time Complexity: O(N)
Space Complexity: O(N)

Solution 2: Two Pointers

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if not head:
            return False
        
        ptrSlow, ptrFast = head, head.next
        while ptrFast != None and ptrFast.next != None:
            ptrSlow = ptrSlow.next
            ptrFast = ptrFast.next.next
            if ptrSlow == ptrFast:
                return True
        return False

Time Complexity: O(N)
Space Complexity: O(1)

Reference

https://leetcode.com/problems/linked-list-cycle/discuss/823960/two-approaches-in-Python-3%3A-dictionary-and-two-pointers


上一篇
[Day 51] Move Zeroes (Easy)
下一篇
[Day 53] Validate Binary Search Tree (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言