[LeetCode] 138. Copy List with Random Pointer
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 138. Copy List with Random Pointer相关的知识,希望对你有一定的参考价值。
拷贝带有随机指针的链表。题意是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的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 138. Copy List with random pointer
LeetCode-138-Copy List with Random Pointer
Leetcode 138. Copy List with Random Pointer
LeetCode 138. Copy List with Random Pointer