码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 138. Copy List with Random Pointer

时间:2020-01-18 11:08:28      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:inter   each   inf   tac   http   with   put   rand   @param   

拷贝带有随机指针的链表。题意是input给了一个带有next和random两个指针的链表,对其进行深度遍历(deep copy)。例子,

技术图片

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]

Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]

两种思路,一是用map存住每个node和他们的random pointer。

时间O(n)

空间O(n)

 1 /**
 2  * @param {Node} head
 3  * @return {Node}
 4  */
 5 var copyRandomList = function(head) {
 6     if (head === null) return null;
 7     let map = new Map();
 8     let cur = head;
 9     while (cur !== null) {
10         map.set(cur, new Node(cur.val, cur.next, cur.random));
11         cur = cur.next;
12     }
13     cur = head;
14     while (cur !== null) {
15         map.get(cur).next = map.get(cur.next) || null;
16         map.get(cur).random = map.get(cur.random) || null;
17         cur = cur.next;
18     }
19     return map.get(head);
20 };

 

另外一种思路是首先复制整个链表,然后将每个链表的random node链接好,再断开原链表和复制的链表。

时间O(n)

空间O(1)

 1 /**
 2  * @param {Node} head
 3  * @return {Node}
 4  */
 5 var copyRandomList = function(head) {
 6     // make copy of each node
 7     let cur = head;
 8     while (cur) {
 9         let next = cur.next;
10         let copy = new Node(cur.val);
11         cur.next = copy;
12         copy.next = next;
13         cur = next;
14     }
15 
16     // set random property
17     cur = head;
18     while (cur) {
19         if (cur.random !== null) {
20             cur.next.random = cur.random.next;
21         }
22         cur = cur.next.next;
23     }
24 
25     // detach copied list
26     cur = head;
27     let dummyHead = new Node(0);
28     let newHead = dummyHead;
29     while (cur) {
30         let next = cur.next.next;
31         // extract the copy
32         let copy = cur.next;
33         newHead.next = copy;
34         newHead = copy;
35         // restore the original list
36         cur.next = next;
37         cur = next;
38     }
39     return dummyHead.next;
40 };

[LeetCode] 138. Copy List with Random Pointer

标签:inter   each   inf   tac   http   with   put   rand   @param   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12208136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!