Sword Pointer Offer (Special Assault Edition) Question 21|22

Preface

  • Now that the front-end requirements have become higher, you may encounter algorithm questions when looking for a job. Be prepared by brushing a few algorithm questions every day. Today is question 21|22 of "Sword Finger Offer (Special Assault Edition)".

Sword Points Offer II 021. Delete the nth node from the bottom of the linked list

Given a linked list, delete the nth node from the bottom of the linked list and return the head node of the linked list.

Difficulty: Moderate

示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5] 

示例 2:
输入:head = [1], n = 1 输出:[] 

示例 3:
输入:head = [1,2], n = 1 输出:[1] 

提示:
● 链表中结点的数目为 sz
● 1 <= sz <= 30
● 0 <= Node.val <= 100
● 1 <= n <= sz

Example 1:

Knowledge points: linked list[1] double pointer[2]

Method 1: Double pointers

This problem becomes simpler if the linked list can be traversed twice. When traversing the linked list for the first time, the total number of nodes in the linked list n can be obtained. When traversing the linked list for the second time, you can find the nk-th node of the linked list (i.e., the k+1-th node from the last). Then point the next pointer of the k+1th node from the bottom to the k-1th node from the bottom, so that the kth node from the bottom can be deleted from the linked list.

If you can only traverse the linked list once. In order to find the k+1th node from the bottom by traversing the linked list only once, two pointers can be defined. The first pointer P1 moves forward k steps starting from the head node of the linked list, and the second pointer P2 remains unchanged; starting from the k+1th step, the pointer P2 also starts from the head node of the linked list and traverses the pointer P1 at the same speed. . Since the distance between the two pointers always remains k, when pointer P1 points to the tail node of the linked list, pointer P2 just points to the k+1th node from the bottom.

 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    let dmy = new ListNode(0, head);
    let slow = dmy;
    let fast = dmy;

    
    while (n > 0) {
        fast = fast.next;
        n--;
    }

    
    while (fast !== null && fast.next !== null) {
        fast = fast.next;
        slow = slow.next;
    }

    
    slow.next = slow.next.next;

    return dmy.next;
};

Complexity analysis

  • Time complexity: O(L), where L is the length of the linked list.

  • Space complexity: O(1)).

Sword Points to Offer II 022. The entry node of the ring in the linked list

Given a linked list, return the first node where the linked list begins to enter the loop. Starting from the head node of the linked list and entering the ring along the next pointer, the first node is the entry node of the ring. If the linked list is loop-free, null is returned.

To represent a cycle in a given linked list, we use the integer pos to represent the position in the linked list where the tail of the linked list is connected (indexing starts from 0). If pos is -1, there is no cycle in the linked list. Note that pos is only used to identify the ring situation and will not be passed to the function as a parameter.

Description: Modification of the given linked list is not allowed.

Difficulty: Moderate

Example 1:

Input: head = [3,2,0,-4], pos = 1 Output: Return the linked list node with index 1 Explanation: There is a ring in the linked list, and its tail is connected to the second node.

Example 2:

Input: head = [1,2], pos = 0 Output: Return the linked list node with index 0 Explanation: There is a ring in the linked list, and its tail is connected to the first node.

Example 3:

Input: head = [1], pos = -1 Output: return null Explanation: There is no cycle in the linked list.

hint:

  • The number of nodes in the linked list ranges from [0, 104]

  • -105 <= Node.val <= 105

  • The value of pos is -1 or a valid index in the linked list

Knowledge points: Hash table[3] Linked list[4] Double pointer[5]

Method 1: Double pointers

If there is no ring in a linked list, then naturally there is no entry node of the ring, and null should be returned.

Inspired by question 21, you can use two pointers to determine whether the linked list contains a ring. You can define two pointers and start from the head node of the linked list at the same time. One pointer moves one step at a time, and the other pointer moves two steps at a time. If the linked list does not contain a cycle, the fast pointer will not meet the slow pointer until it reaches the end node of the linked list. If the linked list contains a ring, the faster pointer will catch up with the slower pointer after going around the ring. Therefore, you can determine whether the linked list contains a ring based on whether two pointers, one fast and one slow, can meet.

Derivation:

  1. Suppose the length of the outer part of the linked list is a. After the slow pointer enters the ring, it travels a distance b and meets fast. At this time, the fast pointer has completed n rounds of the ring, so:

a. The total distance traveled by fast is a + n(b + c) + b =>a + (n + 1)b + nc;

b. The total distance traveled by slow is a + b;

  1. According to the meaning of the question, at any time, the distance traveled by the fast pointer is twice that of the slow pointer.

Then there is a + (n + 1)b + nc = 2(a + b)→a = c + (n - 1)(b + c);

  1. With the equivalence relationship of a = c + (n - 1) (b + c), we will find that the distance c from the meeting point to the loop entry point, plus the loop length of n-1 circles, is exactly equal to the distance from the head of the linked list The distance to the loop entry point;

  2. Therefore, when it is found that slow and fast meet, an additional pointer ptr is used to start pointing to the head of the linked list, and then ptr and slow move backward one position each time, and eventually they will meet at the loop entry point;

 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */


 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function(head) {
    if (head === null || head.next === null) {
        return null;
    }

    let slow = head;
    let fast = head;

    while (fast !== null) {
        slow = slow.next;

        if (fast.next === null) {
            return null;
        }

        fast = fast.next.next;

        
        if (fast === slow) {
            
            let ptr = head;

            
            

            while (ptr !== slow) {
                ptr = ptr.next;
                slow = slow.next;
            }
            return ptr;
        }
        
    }
    return null;
};

Complexity analysis

  • Time complexity: O(N), where N is the number of nodes in the linked list. When initially judging whether the fast and slow pointers meet, the distance traveled by the slow pointer will not exceed the total length of the linked list; when subsequently searching for the loop entry point, the distance traveled will not exceed the total length of the linked list. Therefore, the total execution time is O(N)+O(N)=O(N)

  • Space complexity: O(1). Three pointers, slow, fast, and ptr, are used.

so

  • The ending is still the same: there will be times when the wind and waves break, and the clouds and sails will sail directly to the sea!

  • The online collection is indeed very good. I have summarized and organized the articles, online preparation guide for interviews and question answering. You can take it away without any thanks. You must learn to stand on the shoulders of others and improve yourself. Click here -->

at last:

If you are looking for a job now, you can send a private message to "web" or directly add an assistant to the group to receive the front-end interview brochure, resume optimization and modification, internal recommendations from major manufacturers , and more collections of real interview questions from Alibaba, Byte and major manufacturers , and p8 bosses Communicate together.

Supongo que te gusta

Origin blog.csdn.net/Likestarr/article/details/135360368
Recomendado
Clasificación