[Leetcode] 138. Copy List with Random Pointer 解题报告

xiaoxiao2021-02-27  155

题目:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

思路:

亲耳听一位朋友被Google用这道题目坑的半死,我敢保证我如果第一次碰到这个题目也绝对死翘翘。如果要求用O(n)的空间复杂度,那么地球上绝大多数人都会做,用个哈希表记录一下被clone的节点和原节点的对应关系,然后填充随机指针即可。然而面试官立即会限制你只能用O(1)的空间复杂度,O(n)的时间复杂度。怎么办?因为很可能你当前正在克隆的节点所指向的随机指针目前还没有被克隆出来呢。其实办法很巧妙,和把大象装进冰箱里一样,分三步走:

1)克隆每个节点,并且把克隆的节点插入到原链表中对应节点之后。假设原来链表是A->B->C->D...,则克隆之后的链表变为:A->A'->B->B'->C->C'->D->D'...。

2)设定随机节点。这里利用了1)中对应节点相邻的特性。假如A的随机节点指向了D,那么我们只需要让A'的随机节点指向D之后的元素即可,即D‘。

3)拆分链表。像解拉链一样,把两个链表解开,即可形成复制后的链表A'->B'->C'->D'...。

算法的时间复杂度是O(n),空间复杂度是O(1)。

代码:

/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { if(head == NULL) { return NULL; } // 1) copy each node, and construct the double list RandomListNode *node = head; while(node != NULL) { RandomListNode *node_clone = new RandomListNode(node->label); RandomListNode *node_next = node->next; node->next = node_clone; node_clone->next = node_next; node = node_next; } // 2) copy the random pointer for each node node = head; while(node != NULL) { RandomListNode *node_clone = node->next; if(node->random != NULL) { node_clone->random = node->random->next; } node = node_clone->next; } // 3) seperate the two lists RandomListNode *head_clone = head->next; node = head; while(node != NULL) { RandomListNode *node_clone = node->next; RandomListNode *node_next = node_clone->next; if(node_clone->next == NULL) { // we reach the tail node->next = NULL; } else { node->next = node_clone->next; node_clone->next = node_clone->next->next; } node = node_next; } return head_clone; } };

转载请注明原文地址: https://www.6miu.com/read-15083.html

最新回复(0)