LeeCode142环形链表Ⅱ(Java)(快慢指针和hash哈希两种做法)

题目链接:LeeCode142环形链表Ⅱ
题目描述:在这里插入图片描述
刚做完leetcode141就做这个了,所以对大体思路也都差不多,先写了一个哈希看看能不能过,过是过了但是打败了5%的提交有点太low了,而且题目说要求空间o(1)做

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    
   public static ListNode detectCycle(ListNode head) {
    
    
        List<ListNode> list=new ArrayList<>();
        while(head!=null){
    
    
            if(list.contains(head))return head;
            list.add(head);
            head=head.next;
        }
        return null;
    }
}

写完hash之后考虑我认为这个题真正要考的东西------我觉得还是快慢指针
首先就是类似于高中物理题一样。因为是快慢指针所以有x,y两个物体
x的速度是每秒1,y的速度是每秒2
如果x,y能相遇代表肯定有循环点
当x,y第一次相遇时x=nb(看图)
由题可知我们要求的就是入口也就是距离head a长度的位置,因为x已经等于nb了,所以把快指针y设置成0也就是head时,两个物体同时走a一定会再次相遇,因为a=a+nb
此时两物体所处位置就是循环入口
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    
    public static ListNode detectCycle(ListNode head) {
    
    
        ListNode l=head,r=head;
        while (true) {
    
    
            if(r==null||r.next==null)return null;
            l=l.next;
            r=r.next.next;
            if(l==r)break;
        }
        r=head;
        while (l != r) {
    
    
            l=l.next;
            r=r.next;
        }
        return l;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43590593/article/details/113062530