PROBLEM
剑指 Offer 35. 复杂链表的复制
难度 中等
MY ANSWER
使用哈希表储存原链表节点与新链表节点的对应关系,根据表来构造新链表。时间复杂度空间复杂度都为O(n)。
class Solution { public: unordered_map<Node*, Node*> table; Node* copyRandomList(Node* head) { if(!head) { return nullptr; } Node* tmp = head; Node* dup = NULL; dup = new Node(tmp->val); table[tmp] = dup; tmp = tmp->next; Node* dhead = dup; while (tmp) { dup->next = new Node(tmp->val); dup = dup->next; table[tmp] = dup; tmp = tmp->next; } tmp = head; dup = dhead; while(dup) { if(tmp->random) { dup->random = table[tmp->random]; } else { dup->random = NULL; } tmp = tmp->next; dup = dup->next; } return dhead; } };
|
代码可以更简洁点,先遍历一次创建哈希表,再遍历一次把next、random都构造好。
class Solution { public: Node* copyRandomList(Node* head) { if(head == nullptr) return nullptr; Node* cur = head; unordered_map<Node*, Node*> map; while(cur != nullptr) { map[cur] = new Node(cur->val); cur = cur->next; } cur = head; while(cur != nullptr) { map[cur]->next = map[cur->next]; map[cur]->random = map[cur->random]; cur = cur->next; } return map[head]; } };
|
BETTER SOLUTION
构建 原节点 1 -> 新节点 1 -> 原节点 2 -> 新节点 2 -> ……
的拼接链表,根据拼接链表来设置random和next,时间复杂度相同,空间复杂度减少到O(1)。
class Solution { public: Node* copyRandomList(Node* head) { if(head == nullptr) return nullptr; Node* cur = head; while(cur != nullptr) { Node* tmp = new Node(cur->val); tmp->next = cur->next; cur->next = tmp; cur = tmp->next; } cur = head; while(cur != nullptr) { if(cur->random != nullptr) cur->next->random = cur->random->next; cur = cur->next->next; } cur = head->next; Node* pre = head, *res = head->next; while(cur->next != nullptr) { pre->next = pre->next->next; cur->next = cur->next->next; pre = pre->next; cur = cur->next; } pre->next = nullptr; return res; } };
|
SUMMARY
使用拼接链表来降低空间复杂度。