leetcode linked list cycle

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

一开始没有考虑空间复杂度,借助hashmap找到第一个出现重复的listnode:

Map<ListNode,Integer> map=new HashMap<>();
while(head!=null)
{
    if(map.get(head)==null)
    {
        map.put(head,1);
        head=head.next;
    }
    else return true;

}

return false;
后来看到了只想到了时间复杂度为O(n^2)的方法,对每个节点查找是否有环,效率不高,在网上看到一个很好的方法,以下部分纯转载:

使用两个指针slow,fast。两个指针都从表头开始走,slow每次走一步,fast每次走两步,如果fast遇到null,则说明没有环,返回false;如果slow==fast,说明有环,并且此时fast超了slow一圈,返回true。

为什么有环的情况下二者一定会相遇呢?因为fast先进入环,在slow进入之后,如果把slow看作在前面,fast在后面每次循环都向slow靠近1,所以一定会相遇,而不会出现fast直接跳过slow的情况。


代码如下:

public boolean hasCycleII(ListNode head) {
    ListNode fast=head;
    ListNode slow=head;
    do
    {
        if(slow==null||fast==null)
            return false;
        slow=slow.next;
        fast=fast.next;
        if(fast==null)
            return false;
        fast=fast.next;
    }while(slow!=fast);
    return true;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值