141. 环形链表【简单】

题目

给你一个链表的头节点 head ,判断链表中是否有环。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。

如果链表中存在环 ,则返回 true 。 否则,返回 false 。

在这里插入图片描述
在这里插入图片描述

自解

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode current = head, tail = head;

        while(tail != null){
            tail = tail.next;
            if(tail == null) break;
            current = head;
            while(current != tail && tail.next != current){
                current = current.next;
            }
            if(tail.next == current)
                return true;
        }
        return false;
    }
}

边界条件current != tail判断有误,写成了current.next != tail,少考虑了一种尾部自己指向自己循环的情况,导致以下例子没有通过:

[-1,-7,7,-4,19,6,-9,-5,-2,-5]
9

只要弄清楚判断条件是 tail.next == current且保证current在循环向后的过程中不超过tail所指节点,基本没什么困难。但此方法时间复杂度是O(n*n)级别的。


题解

看了题解,使用哈希表就不用从头再找了。应用HashSet。时间复杂度和空间复杂度都为O(n)。优化如下:

public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> set = new HashSet<ListNode>();
        while(head != null){
            if(!set.add(head))
                return true;
            head = head.next;
        }
        return false;
    }
}

优雅!


题解二

Floyd判断法/龟兔赛跑算法

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null){
            return false;
        }
        ListNode fast = head.next, slow = head;
        while(fast != slow){
            if(fast == null || fast.next == null){
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}

学到了!很中!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值