Floyd判圈算法

Floyd判圈算法又称龟兔赛跑算法(Tortoise and Hare Algorithm),是一个可以在有限状态机、迭代函数或者链表上判断是否存在环,求出该环的起点与长度的算法。
如果有限状态机、迭代函数或者链表上存在环,那么在某个环上以不同速度前进的2个指针必定会在某个时刻相遇。同时显然地,如果从同一个起点(即使这个起点不在某个环上)同时开始以不同速度前进的2个指针最终相遇,那么可以判定存在一个环,且可以求出2者相遇处所在的环的起点与长度。

以 leetcode 141. 环形链表 为例:https://leetcode-cn.com/problems/linked-list-cycle/

my solution

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

        return false;
    }

offcial solution

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

leetcode 142 依然是应用此算法 :https://leetcode-cn.com/problems/linked-list-cycle-ii/

 public ListNode offcialSolution2(ListNode head){
        if(head==null){
            return null;
        }
        ListNode slow=head, fast=head;
        while(fast!=null){
            slow=slow.next;
            if(fast.next!=null){
                fast = fast.next.next;
            }else{
                return null;
            }
            //说明有环
            if(fast==slow){
                ListNode ptr = head;
                while(ptr !=slow){
                    ptr =ptr.next;
                    slow=slow.next;
                }
                return ptr;
            }
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值