首页 > 其他 > 详细

leetcode-142-环形链表②

时间:2019-07-17 11:27:41      阅读:105      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

技术分享图片

方法一:O(n) O(n)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        visited = set()
        node = head
        while node:
            if node in visited:
                #return visited.index(head.val)
                return node
            else:
                visited.add(node)
                node = node.next
        return None

方法二:快慢指针 O(N) O(1)

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        fast, slow = head, head 
        while True: 
            if not (fast and fast.next): 
                return 
            fast, slow = fast.next.next, slow.next 
            if fast == slow: 
                break 
        fast = head 
        while fast != slow: 
            fast, slow = fast.next, slow.next 
        return fast

 

leetcode-142-环形链表②

原文:https://www.cnblogs.com/oldby/p/11199575.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!