刷題筆記 - 0422

一、clone graph   用map結構存儲原值和拷貝值,一一對應。node

map紅黑樹實現,O(logn) 內部有序;每一個節點要保存父節點、子節點及紅黑屬性,佔用空間大。數組

unordered_map哈希表實現,查找O(1),內部無序;哈希表創建耗時。   經常使用unordered_mapspa

class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        // 拷貝全部點  DFS寫法
        if (!node)  return nullptr;
        unordered_map<int, UndirectedGraphNode *> table;
        return helper(node, table);
    }
    
    UndirectedGraphNode *helper(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode*>& table) {
        if (!node)  return nullptr;
        // 若是表中已有數據
        if (table.find(node->label) != table.end()) {
            return table[node->label];
        }
        UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
        table[node->label] = newNode;
        for (int i = 0; i < node->neighbors.size(); i++) {
            UndirectedGraphNode *tmp = helper(node->neighbors[i], table);
            newNode->neighbors.push_back(tmp);
        }
        return newNode;
    }
};

 

 1 /**
 2  * Definition for undirected graph.
 3  * struct UndirectedGraphNode {
 4  *     int label;
 5  *     vector<UndirectedGraphNode *> neighbors;
 6  *     UndirectedGraphNode(int x) : label(x) {};
 7  * };
 8  */
 9 class Solution {
10 public:
11     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
12         // 拷貝全部點  用BFS或DFS遍歷均可以  是否已拷貝用map判斷
13         if (!node)  return nullptr;
14         unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> map;
15         UndirectedGraphNode *p1 = node;
16         UndirectedGraphNode *p2 = new UndirectedGraphNode(node->label);
17         queue<UndirectedGraphNode *> q;
18         q.push(node);
19         map[p1] = p2;
20         while (!q.empty()) {
21             p1 = q.front();   q.pop();
22             p2 = map[p1];
23             for (int i = 0; i < p1->neighbors.size(); i++) {
        // 注意對鄰接點的判斷 若map中已有,則直接設置p2的鄰接點;不然插入map,入隊列處理
24 UndirectedGraphNode *tmp = p1->neighbors[i]; 25 if (map.count(tmp) != 0) { 26 p2->neighbors.push_back(map[tmp]); 27 } else { 28 UndirectedGraphNode *copy = new UndirectedGraphNode(tmp->label); 29 map[tmp] = copy; 30 p2->neighbors.push_back(map[tmp]); 31 q.push(tmp); 32 } 33 } 34 } 35 return map[node]; 36 } 37 };

二、二叉樹序列化    https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93167/Concise-C++-19ms-solution-beating-99.4code

隊列的數組實現與鏈表實現,用vector實現queueblog

相關文章
相關標籤/搜索