力扣刷题笔记5——复杂链表的复制以及unordered_map的学习
问题
力扣的题:
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next
指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例 1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例代码
我没想出来这么搞,没记起来C++有字典类型的容器,所以后面就直接看了答案。
/*
// 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) {
if(!head){
return NULL;
}
Node* cur = head;
unordered_map<Node*,Node*> map;
while(cur!=nullptr){
map[cur] = new Node(cur->val);
cur = cur->next;
}
cur = head;
while(cur!=nullptr){
map[cur]->next = map[cur->next];
map[cur]->random = map[cur->random];
cur = cur->next;
}
return map[head];
}
};
unordered_map
感觉和python里的字典一样。
下面是我从网上找的一些内容:
- 定义
template < class Key, //键值对中键的类型
class T, //键值对中值的类型
class Hash = hash<Key>, //容器内部存储键值对所用的哈希函数
class Pred = equal_to<Key>, //判断各个键值对键相同的规则
class Alloc = allocator< pair<const Key,T> > // 指定分配器对象的类型
> class unordered_map;
从定义可以看到,前两个对应的是键和值,创建的时候至少需要给出这两个的类型。
- 创建方法
1通过调用 unordered_map 模板类的默认构造函数,可以创建空的 unordered_map 容器。
std::unordered_map<std::string, std::string> umap;
2在创建 unordered_map 容器的同时,可以完成初始化操作。
std::unordered_map<std::string, std::string> umap{
{"Python教程","http://c.biancheng.net/python/"},
{"Java教程","http://c.biancheng.net/java/"},
{"Linux教程","http://c.biancheng.net/linux/"} };
3在第二种方式创建好 umap 容器的基础上,再创建并初始化一个 umap2 容器。
std::unordered_map<std::string, std::string> umap2(umap);
4不全部拷贝,包含 umap 容器中除第 1 个键值对外的所有其它键值对。
std::unordered_map<std::string, std::string> umap2(++umap.begin(),umap.end());