刷題筆記 - 0422
阿新 • • 發佈:2018-04-23
有序 n) ng- 所有 ron 遍歷 tab .com directed
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
刷題筆記 - 0422