1、clone graph 用map结构存储原值和拷贝值,一一对应。
map红黑树实现,O(logn) 内部有序;每个节点要保存父节点、子节点及红黑属性,占用空间大。
unordered_map哈希表实现,查找O(1),内部无序;哈希表建立耗时。 常用unordered_map
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 };
2、二叉树序列化 https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93167/Concise-C++-19ms-solution-beating-99.4
队列的数组实现与链表实现,用vector实现queue
原文地址:https://www.cnblogs.com/li-ling/p/8911518.html
时间: 2024-11-06 07:15:48