iT邦幫忙

2023 iThome 鐵人賽

DAY 5
0
自我挑戰組

leetcode題目分享系列 第 5

[Day 5] 138. Copy List with Random Pointer

  • 分享至 

  • xImage
  •  

參考了這篇>https://leetcode.com/problems/copy-list-with-random-pointer/solutions/4003262/97-92-hash-table-linked-list/?envType=daily-question&envId=2023-09-05

hashmap具有索引性,用來對付pointer of random相當適合。此解法先將每個節點掛在hashmap,再重走一遍把該串的串起來,最後回傳head的點。

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        unordered_map<Node*, Node*> umap;
        Node* curr = head; 

        while(curr){
            umap[curr] = new Node(curr->val);
            curr = curr->next;
        }

        curr = head;

        while(curr){
            umap[curr]->next = umap[curr->next];
            umap[curr]->random = umap[curr->random];
            curr = curr->next;
        }
        return umap[head];
    }
};

上一篇
[Day 4] 141. Linked List Cycle
下一篇
[Day 6] 725. Split Linked List in Parts
系列文
leetcode題目分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言