Title link: LeeCode142 Circular Linked List II
Title description:
I did this right after I finished leetcode141, so the general idea is the same, first write a hash to see if it can be passed, it passed but defeated 5% of submissions It’s a bit too low, and the title says it requires space o(1) to do
/**
* 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;
}
}
After writing the hash, consider what I think this question really needs to be tested ------ I think it is still a quick and slow pointer.
First of all, it is similar to high school physics questions. Because it is a fast and slow pointer, there are two objects
x and y. The speed of x is 1 per second, and the speed of y is 2 per second.
If x and y can meet, there must be a loop point.
When x and y meet for the first time, x=nb (Look at the picture)
From the question, we can see that what we require is the entrance, which is the position from the length of head a, because x is already equal to nb, so when the fast pointer y is set to 0, that is, head, two objects will move at the same time. Meet, because a=a+nb
where the two objects are now is the loop entrance
/**
* 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;
}
}