C++采用哈希表,时间复杂度O(n),空间复杂度O(n)空间复杂度应该可以降低;
/* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node() {} Node(int _val, Node* _next, Node* _random) { val = _val; next = _next; random = _random; } }; */ class Solution { public: Node* copyRandomList(Node* head) { //建立哈希表遍历两次,一次复制next并填充哈希表,第二次复制random unordered_map<Node*,Node*> h; Node *pre, *cur, *root; pre=root=new Node(-1,NULL,NULL); cur=head; while(cur!=NULL){ int v=cur->val; Node *p=new Node(v,NULL,NULL); h[cur]=p; pre->next=p; pre=p; cur=cur->next; } cur=root->next; pre=head; h[NULL]=NULL; while(cur!=NULL){ cur->random=h[pre->random]; cur=cur->next; pre=pre->next; } return root->next; } };
原文地址:https://www.cnblogs.com/joelwang/p/11050382.html
时间: 2024-11-10 01:57:52