首页 > 其他 > 详细

【Leetcode链表】环形链表(141)

时间:2019-11-24 22:04:46      阅读:97      评论:0      收藏:0      [点我收藏+]

题目

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

技术分享图片

示例 2:

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。

技术分享图片

示例 3:

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

技术分享图片

进阶:你能用 O(1)(即,常量)内存解决此问题吗?

解答

三种方法:
1,遍历整个链表,看能不能走到尾部NULL,如果有NULL则无环,如果没有NULL就可能是有环,也可能链表太长会运行超时,这种方法不可取
2,用哈希表,依次遍历链表set存储走过的点 ———— 时间复杂度O(n),空间复杂度O(n)
3,快慢指针,如果有环快指针一定会追上慢指针,两者相遇即有环,快指针走到NULL即无环 ———— 时间复杂度O(n),空间复杂度O(1)

通过代码如下:

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

## 哈希set,对比走过的点
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        s = set()
        while head:
            if head in s:
                return True
            s.add(head)
            head = head.next
        return False
## 时间复杂度O(n),空间复杂度O(n)


## 快慢指针,快指针一次走两步,慢指针走一步,如果有环快慢一定会相遇
# class Solution:
#     def hasCycle(self, head: ListNode) -> bool:
#         f = s = head
#         while f and f.next:  # 一定是f.next不能为空,因为f走得快
#             f = f.next.next
#             s = s.next
#             if f == s:
#                 return True
#         return False
## 时间复杂度O(n),空间复杂度O(1)

【Leetcode链表】环形链表(141)

原文:https://www.cnblogs.com/ldy-miss/p/11924293.html

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