/*// 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; }};*/classSolution {public:Node*copyRandomList(Node* head) {if(!head) returnNULL; Node* newHead =newNode(0); Node* ptr = newHead; map<Node*, Node*> table; Node* itr = head;while(itr) {ptr->next =newNode(itr->val);ptr->next->next =itr->next;table.insert(pair<Node*,Node*>(itr,ptr->next) ); itr =itr->next; ptr =ptr->next; } itr = head;while(itr) {table[itr]->random =table[itr->random]; itr =itr->next; }returnnewHead->next; }};/*pseudo code:create a map<Node*, Node*>create new head & ptrgo through the old list copy all nodes' value and next to the new list store the old node and new node pair to mapgo through the old list set the corresponding new node's random to old node's random's new nodereturn new head*/
實際跑起來的時間如下:
Runtime: 32 ms, faster than 93.26% of C++ online submissions for Copy List with Random Pointer. Memory Usage: 22.3 MB, less than 16.81% of C++ online submissions for Copy List with Random Pointer.
解法二 - 每個 node 都先複製一份,再分離出來
這個解法滿聰明的,主要是希望在每個 node 後面複製一份同樣的 node,這樣就不需要像解法一用額外的空間去存 old list node 跟 new list node 之間的對應關係。
Runtime: 36 ms, faster than 82.83% of C++ online submissions for Copy List with Random Pointer. Memory Usage: 22.2 MB, less than 29.43% of C++ online submissions for Copy List with Random Pointer.