Copy List with Random Pointer
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 adeep copyof the list.
Example 1:

Note:
You must return the copy of the given head as a reference to the cloned list.
Solution & Analysis
HashMap 保存 old -> copy的映射,避免重复创建新Node。这样会用到O(n) space.
Approach 1: Recursion with O(N) Space
Complexity Analysis
Time Complexity: O(N) where N is the number of nodes in the linked list.
Space Complexity: O(N). If we look closely, we have the recursion stack and we also have the space complexity to keep track of nodes already cloned i.e. using the visited dictionary. But asymptotically, the complexity is O(N).
*Approach 2: Iterative with O(N) Space
**Approach 3: Iterative with O(1) Space
比较巧妙的方法是,weave new node and old node, 利用位置关系,设定random指针,最后unweave。
A -> A' -> B -> B' -> C -> C'
Complexity Analysis
Time Complexity : O(n)
Space Complexity : O(1)
Reference
https://leetcode.com/problems/copy-list-with-random-pointer/solution/
Last updated
Was this helpful?