Rabbit series brush questions leetcode series three fast and slow pointers

Speed ​​pointer

Common pattern

Related to the
linked list, determine whether the linked list has loops, etc.

The first circular linked list

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-X6jlNhcv-1585725826423)(442FE650C2B4416BA0F33FB51EB9427D)]
[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-GqlXR2qT-1585725826425)(8385C5AA56EB47C1A7A98404F8DE9C1A)] [External link image transfer failed, the source site may have an anti-leech link mechanism, It is recommended to save the picture and upload it directly (img-ELZYyOuN-1585725826430) (D8848E7863EB4436BF4C3E6B07A4A282))

Ideas:

If the linked list is a circular linked list, then we can define two pointers, one moves forward two nodes at a time, and the other moves forward one node at a time. This is the same as the track and field competition. If the two athletes run straight, the fast athlete and the slow athlete are at the same position at the starting point, but the fast athlete will reach the end first, during which the two athletes will not Meet. And if you run in circles (assuming there is no limit on the number of meters), the fast athletes will meet when they exceed the slow athletes by one lap. At this moment, it is a circular linked list.

The difference with the tortoise and the hare:

Regarding the speed of the two pointers in the fast and slow pointers: Unlike the tortoise and the hare race, the tortoise and the hare race is a continuity problem. No matter how much the speed difference between the two is, it can be assumed as follows: assuming the track length is s, v_f represents the value of fast speed, v_s represents the value of slow speed, (assuming that the initial positions of the two are the same), then you can find: (v_f-v_s)t=s; the t calculated in this way is the first time the two meet The difference in this question is: for the linked list, it is a discrete value. We assume that there are n nodes in the ring. Also assume that the fast pointer and the slow pointer are v_f and v_s respectively; if you want to meet (assuming the same initial position) , Also have (v_f-v_s)k = n; ——At this time v_f, v_s are positive integers, k is the number of cycles, and n is the number of nodes; k = n/(v_f-v_s) If you want k to be an integer, then It can be seen that the speed difference between the two is required, and must be divisible by n; Note: This is the first time that it meets, and it is also possible that v_f-v_s is an integer multiple of n;

Code:

/**
 * 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) {
    
    
        if(head==null)
		    	return false;
	        ListNode p=head;
	        ListNode q=head;
	        while(p!=null&&q!=null)
	        {
    
    
	        	p=p.next;
                if(q.next==null)
                    return false;
	        	q=q.next.next;
	        	if(p.equals(q))
	        	{
    
    
	        		return true;
	        	}
	        }
	        return false;
    }
}

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-OMCxUWha-1585725826431)(8477DAC96AF84806B94FD8D199D1D005)]

The second circular linked list

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-O0y7qasT-1585725826433)(3B0D18ED5FBE47308DF9A3C13A55D142)]
[External link image transfer failed, the source site may have an anti-leech link mechanism, it is recommended to save the image and upload it directly (img-AnLiVQsb-1585725826435)(E3ADA207DBD34E3095307D12A6F909AE)] [External link image transfer failed, the origin site may have an anti-leech link mechanism, It is recommended to save the picture and upload it directly (img-8PR3Scmn-1585725826436)(E9EBF2CBBF19492FAEC3E23519308EF6))

Ideas:

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-tROPtcOi-1585725826438)(9806B5338D2C46698C0471924351B9CD)]
As shown in the figure, suppose that there are a node
in a non-ring and b nodes in a ring
.

fast走的节点数=2*slow走的节点数\\

fast走的节点数-slow走的节点数=nb(多走了n圈)
第一次相遇时slow走的节点数为nb
一个节点走a+nb步一定会在入口处
slow在第一次相遇后再走a步即可
可以第一次相遇后,设置一个指针从头开始,以slow的速度,两者相遇时即为入口

Code:

public class Solution {
    
    
    public ListNode detectCycle(ListNode head) {
    
    
       if(head==null)
		    	return null;
	        ListNode p=head;
	        ListNode q=head;
            if(head.next==null)
            {
    
    
                return null;
            }
	        while(p!=null&&q!=null)
	        {
    
    
	        	p=p.next;
                if(q.next==null)
                return null;
	        	q=q.next.next;
	        	if(p.equals(q))
	        	{
    
    
	        		q=head;
	        		while(p!=null&&q!=null)
	        		{
    
    
                        if(p.equals(q))
	        			{
    
    
	        				return p;
	        			}
	        			q=q.next;
	        			p=p.next;
	        		
	        		}
	        	}
	        }
	        return null;
    }
}

The middle node of the third linked listInsert picture description here

[External link image transfer failed, the source site may have an anti-leech link mechanism, it is recommended to save the image and upload it directly (img-IkHYOtRQ-1585725826441)(62E78BABD53B4093A6A139F116D547F5)]

Ideas:

The fast pointer crosses two nodes at a time; the
slow pointer crosses one node at a time; when the
fast pointer reaches the end, the slow pointer reaches the middle position.

Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public ListNode middleNode(ListNode head) {
    
    
        		ListNode fast=head;
		ListNode slow=head;
		while(true)
		{
    
    
			if(fast.next==null)
			{
    
    
				return slow;
			}
			if(fast.next.next==null)
			{
    
    
				slow=slow.next;
				return slow;
			}
			else {
    
    
				fast=fast.next.next;
				slow=slow.next;
			}
		}
    }
}

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-UscIrkNx-1585725826442)(158B160E1E5A4DB691DBB5D0AA6BD1A1)]

The fourth way is to delete the nth node from the bottom of the linked list

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-vynUVmOn-1585725826444)(784223AA3A9D4511B33666FB30A52F12)]

Ideas:

The fast pointer
goes n nodes first, then the fast and slow pointers go down one node
at a time. When the fast pointer reaches the end,
the position reached by the slow pointer is the nth node from the bottom.

Code:

public static ListNode deleteNode(ListNode head,int n) {
    
    
		ListNode p=head;
		ListNode q=head;
		for(int i=0;i<n-1;i++)
		{
    
    
			p=p.next;
		}
		while(true)
		{
    
    
			if(p.next.next==null)
			{
    
    
				q.next=q.next.next;
				return head;
			}
			p=p.next;
			q=q.next;
		}
    }

Guess you like

Origin blog.csdn.net/hch977/article/details/105246980