/*
// 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:
//因为unordered_map是基于哈希表的,只要能用==比较就可以作为key;而map基于红黑树,要满足可以做<运算,所以这里不用map。
Node* copyRandomList(Node* head) {
if(head == nullptr) return nullptr;
Node* org = head;
unordered_map<Node*, Node*> mm;
//复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
while(org != nullptr) {
mm[org] = new Node(org->val);
org = org->next;
}
org = head;
//构建新链表的 next 和 random 指向
while(org != nullptr) {
map[org]->next = map[org->next];
map[org]->random = map[org->random];
org = org->next;
}
return map[head];
}
};
先来一个表格认识一下核心区别

【念叨】文字上的原理解释
map
基本原理
- 底层数据结构:红黑树
std::map 的底层是红黑树,每个节点存储一个键值对(std::pair<const Key, Value>)。红黑树通过一套颜色规则(节点分为红 / 黑两种)保证树的 “近似平衡”,避免出现极端倾斜的情况,从而确保插入、删除、查找等操作的时间复杂度稳定在 O(log n)。 - 键的有序性与映射逻辑
红黑树是一种有序树,std::map 会根据键的比较规则(默认使用 std::less,即小于运算符)对键进行排序。
插入键值对时,会根据键的大小找到红黑树中的合适位置,确保树的有序性;
查找键时,从根节点开始,通过键的比较(小于则向左子树查找,大于则向右子树查找)快速定位到目标节点,进而获取对应的值。
这种基于键的有序性和比较操作的查找逻辑,才是实现 “键到值映射” 的核心。
往map中插入一个键值对时,背后发生什么?
当我们向 std::map 中插入键值对(如 map.insert({key, value}) 或 map[key] = value)时,其内部过程可概括为:
- 键的比较与位置查找
从红黑树的根节点开始,通过比较器(默认 std::less)将新键与当前节点的键比较:
若新键 < 当前节点的键:向左子树查找;
若新键 > 当前节点的键:向右子树查找;
若相等(!(a < b) && !(b < a)):视为键已存在,插入失败(insert 会返回已存在的迭代器)。 - 创建新节点并插入
找到合适的空位后,通过分配器创建新节点,存储键值对,并将新节点链接到红黑树中(设置父节点和左右子节点指针)。新节点初始颜色通常为「红色」。 - 红黑树的平衡调整
插入新节点后,可能破坏红黑树的规则(如连续红节点),因此需要通过以下操作恢复平衡:
变色:修改节点的颜色(红→黑或黑→红);
旋转:包括左旋和右旋(调整节点的父子关系,不改变键的有序性)。
调整的最终目标是保证树的高度维持在 O(log n),确保后续操作的效率。
更新容器管理信息 - 插入成功后,更新 size 计数器,若插入的是新的最小 / 最大键,还需更新 begin()/rbegin() 指向的节点。
unordered_map
基本原理
核心原理是基于哈希表实现键值对映射:通过哈希函数将键转换为整数(哈希值),再将哈希值映射到哈希表的「桶(Bucket)」索引,以此快速定位键值对的存储位置;同时使用「链地址法」处理哈希冲突(不同键可能产生相同哈希值),即每个桶对应一个链表,冲突的键值对会被存储在同一桶的链表中。这种设计使得插入、查找、删除的平均时间复杂度为 O(1)。
往map中插入一个键值对时,又发生什么?
- 计算哈希值:通过哈希函数(如 std::hash)将键转换为一个整数哈希值。
- 映射到桶索引:将哈希值通过取模等运算映射到哈希表的某个桶索引(确定存储的桶位置)。
- 检查冲突与键是否存在:遍历该桶对应的链表,通过相等性比较(如 ==)检查键是否已存在。若存在,则插入失败;若不存在,则创建新节点并插入到链表中(通常为头插法)。
- 判断是否需要重哈希:插入后若当前负载因子(元素总数 / 桶数量)超过阈值(默认 1.0),则触发重哈希:创建更大的桶数组,重新计算所有现有键的哈希值并映射到新桶中,以降低负载因子、减少冲突,维持高效操作。
【代码】从底层源码和应用上认识区别
对进一步挖掘实现原理不感兴趣的朋友,到这里可以退出了,因为接下来的内容和代码占比比较多
map
通过阅读源码我们可以自己尝试用红黑树实现一个my_map.h
- 实现map都需要什么?核心要点主要如下:
- 红黑树的实现,包括节点结构(键值对、指针、颜色);
- 旋转操作(左旋 / 右旋)用于调整树结构;
- 插入后通过变色和旋转修复红黑树的 5 条规则(保证平衡);
- 迭代器需按键的顺序遍历(通过找右子树最左节点或祖先节点实现)。
#include <iostream>
#include <utility> // for pair
// 红黑树节点颜色
enum Color { RED, BLACK };
template <typename Key, typename Value>
struct RBNode {
std::pair<const Key, Value> data; // 键值对(键不可修改)
RBNode* left; // 左子节点
RBNode* right; // 右子节点
RBNode* parent; // 父节点
Color color; // 节点颜色
RBNode(const Key& k, const Value& v)
: data({k, v}), left(nullptr), right(nullptr), parent(nullptr), color(RED) {}
};
template <typename Key, typename Value>
class MyMap {
private:
using Node = RBNode<Key, Value>;
Node* root; // 根节点
size_t size_; // 元素数量
// 辅助函数:左旋
void rotateLeft(Node* x) {
Node* y = x->right;
x->right = y->left;
if (y->left != nullptr) {
y->left->parent = x;
}
y->parent = x->parent;
if (x->parent == nullptr) {
root = y; // x是根节点时,旋转后y成为新根
} else if (x == x->parent->left) {
x->parent->left = y;
} else {
x->parent->right = y;
}
y->left = x;
x->parent = y;
}
// 辅助函数:右旋
void rotateRight(Node* y) {
Node* x = y->left;
y->left = x->right;
if (x->right != nullptr) {
x->right->parent = y;
}
x->parent = y->parent;
if (y->parent == nullptr) {
root = x; // y是根节点时,旋转后x成为新根
} else if (y == y->parent->right) {
y->parent->right = x;
} else {
y->parent->left = x;
}
x->right = y;
y->parent = x;
}
// 插入后修复红黑树平衡
void fixInsert(Node* z) {
while (z->parent != nullptr && z->parent->color == RED) {
if (z->parent == z->parent->parent->left) {
Node* y = z->parent->parent->right; // 叔叔节点
if (y != nullptr && y->color == RED) {
// 情况1:叔叔为红,只需变色
z->parent->color = BLACK;
y->color = BLACK;
z->parent->parent->color = RED;
z = z->parent->parent;
} else {
// 情况2:叔叔为黑,且z是右孩子(先左旋转为情况3)
if (z == z->parent->right) {
z = z->parent;
rotateLeft(z);
}
// 情况3:叔叔为黑,且z是左孩子(右旋+变色)
z->parent->color = BLACK;
z->parent->parent->color = RED;
rotateRight(z->parent->parent);
}
} else {
// 对称情况(父节点是右孩子)
Node* y = z->parent->parent->left;
if (y != nullptr && y->color == RED) {
z->parent->color = BLACK;
y->color = BLACK;
z->parent->parent->color = RED;
z = z->parent->parent;
} else {
if (z == z->parent->left) {
z = z->parent;
rotateRight(z);
}
z->parent->color = BLACK;
z->parent->parent->color = RED;
rotateLeft(z->parent->parent);
}
}
}
root->color = BLACK; // 根节点必须为黑
}
// 查找节点(辅助函数)
Node* findNode(const Key& key) const {
Node* current = root;
while (current != nullptr) {
if (key < current->data.first) {
current = current->left;
} else if (current->data.first < key) {
current = current->right;
} else {
return current; // 找到键
}
}
return nullptr; // 未找到
}
public:
// 迭代器(简化版,仅支持正向遍历)
class Iterator {
private:
Node* node;
public:
Iterator(Node* n) : node(n) {}
std::pair<const Key, Value>& operator*() const {
return node->data;
}
Iterator& operator++() {
// 找下一个节点:右子树的最左节点,或第一个祖先节点(当前是左孩子时)
if (node->right != nullptr) {
node = node->right;
while (node->left != nullptr) {
node = node->left;
}
} else {
Node* parent = node->parent;
while (parent != nullptr && node == parent->right) {
node = parent;
parent = parent->parent;
}
node = parent;
}
return *this;
}
bool operator!=(const Iterator& other) const {
return node != other->node;
}
};
// 构造函数
MyMap() : root(nullptr), size_(0) {}
// 插入键值对(若键已存在则不插入)
void insert(const Key& key, const Value& value) {
Node* z = new Node(key, value);
Node* y = nullptr;
Node* x = root;
// 找到插入位置
while (x != nullptr) {
y = x;
if (z->data.first < x->data.first) {
x = x->left;
} else if (x->data.first < z->data.first) {
x = x->right;
} else {
// 键已存在,直接删除新节点并返回
delete z;
return;
}
}
z->parent = y;
if (y == nullptr) {
root = z; // 树为空,z成为根节点
} else if (z->data.first < y->data.first) {
y->left = z;
} else {
y->right = z;
}
size_++;
fixInsert(z); // 修复红黑树平衡
}
// 查找值(返回 nullptr 表示未找到)
Value* find(const Key& key) const {
Node* node = findNode(key);
return (node != nullptr) ? &(node->data.second) : nullptr;
}
// 重载[]运算符(简化版,不存在则插入默认值)
Value& operator[](const Key& key) {
Node* node = findNode(key);
if (node == nullptr) {
insert(key, Value()); // 插入默认值
node = findNode(key);
}
return node->data.second;
}
// 获取大小
size_t size() const { return size_; }
// 迭代器起始位置(最小键)
Iterator begin() const {
Node* current = root;
while (current != nullptr && current->left != nullptr) {
current = current->left;
}
return Iterator(current);
}
// 迭代器结束位置
Iterator end() const {
return Iterator(nullptr);
}
// 析构函数(释放内存)
~MyMap() {
// 简化版:递归删除所有节点
auto destroy = [](Node* node, auto& self) {
if (node != nullptr) {
self(node->left, self);
self(node->right, self);
delete node;
}
};
destroy(root, destroy);
}
};
当然,自己实现的头文件,效率肯定是比不上库文件的,而且也做了简化再简化,但是可以帮助我们更深地了解原理。
- 简化具体内容:
- 仅支持 int 类型键(如需支持其他类型,需扩展哈希函数和比较器);
- 忽略了标准库中的内存分配器、复制 / 移动语义、异常安全等复杂特性;
- 红黑树的删除操作未实现(较复杂,需额外处理 6 种情况)。
unordered_map
#include <iostream>
#include <utility> // for pair
#include <vector>
#include <cstddef> // for size_t
// 哈希表节点(链表结构,处理冲突)
template <typename Key, typename Value>
struct HashNode {
std::pair<const Key, Value> data; // 键值对(键不可修改)
HashNode* next; // 下一个节点(同桶内)
HashNode(const Key& k, const Value& v) : data({k, v}), next(nullptr) {}
};
// 简化的哈希函数(仅支持int类型键)
struct IntHash {
size_t operator()(int key) const {
return static_cast<size_t>(key); // 直接用键作为哈希值(实际需更复杂的哈希)
}
};
// 相等性比较器(仅支持int类型键)
struct IntEqual {
bool operator()(int a, int b) const {
return a == b;
}
};
template <typename Key, typename Value,
typename Hash = IntHash,
typename KeyEqual = IntEqual>
class MyUnorderedMap {
private:
using Node = HashNode<Key, Value>;
std::vector<Node*> buckets; // 桶数组(每个桶是链表头指针)
size_t size_; // 元素数量
Hash hasher; // 哈希函数对象
KeyEqual keyEqual; // 相等性比较对象
const float maxLoadFactor = 1.0f; // 最大负载因子(超过则扩容)
// 计算桶索引
size_t getBucketIndex(const Key& key) const {
return hasher(key) % buckets.size();
}
// 重哈希(扩容)
void rehash() {
size_t oldBucketCount = buckets.size();
std::vector<Node*> oldBuckets = std::move(buckets);
// 新桶数量为原大小的2倍(至少为1)
size_t newBucketCount = (oldBucketCount == 0) ? 1 : oldBucketCount * 2;
buckets.resize(newBucketCount, nullptr);
size_ = 0;
// 将旧桶中的节点重新映射到新桶
for (size_t i = 0; i < oldBucketCount; ++i) {
Node* current = oldBuckets[i];
while (current != nullptr) {
Node* next = current->next;
// 插入新桶
size_t newIndex = getBucketIndex(current->data.first);
current->next = buckets[newIndex];
buckets[newIndex] = current;
size_++;
current = next;
}
}
}
public:
// 迭代器(简化版)
class Iterator {
private:
Node* current; // 当前节点
const std::vector<Node*>& buckets; // 桶数组
size_t bucketIndex; // 当前桶索引
public:
Iterator(Node* n, const std::vector<Node*>& b, size_t idx)
: current(n), buckets(b), bucketIndex(idx) {}
std::pair<const Key, Value>& operator*() const {
return current->data;
}
Iterator& operator++() {
// 先找当前桶的下一个节点
if (current->next != nullptr) {
current = current->next;
} else {
// 当前桶遍历完,找下一个非空桶
bucketIndex++;
while (bucketIndex < buckets.size() && buckets[bucketIndex] == nullptr) {
bucketIndex++;
}
current = (bucketIndex < buckets.size()) ? buckets[bucketIndex] : nullptr;
}
return *this;
}
bool operator!=(const Iterator& other) const {
return current != other.current;
}
};
// 构造函数
MyUnorderedMap() : size_(0) {
buckets.resize(4); // 初始桶数量为4
}
// 插入键值对(若键已存在则不插入)
void insert(const Key& key, const Value& value) {
// 检查是否需要扩容
if (size_ >= buckets.size() * maxLoadFactor) {
rehash();
}
size_t index = getBucketIndex(key);
Node* current = buckets[index];
// 检查键是否已存在
while (current != nullptr) {
if (keyEqual(current->data.first, key)) {
return; // 键已存在,不插入
}
current = current->next;
}
// 插入新节点(头插法)
Node* newNode = new Node(key, value);
newNode->next = buckets[index];
buckets[index] = newNode;
size_++;
}
// 查找值(返回 nullptr 表示未找到)
Value* find(const Key& key) const {
if (buckets.empty()) return nullptr;
size_t index = getBucketIndex(key);
Node* current = buckets[index];
while (current != nullptr) {
if (keyEqual(current->data.first, key)) {
return &(current->data.second);
}
current = current->next;
}
return nullptr;
}
// 重载[]运算符(简化版)
Value& operator[](const Key& key) {
Value* val = find(key);
if (val == nullptr) {
insert(key, Value());
val = find(key);
}
return *val;
}
// 获取大小
size_t size() const { return size_; }
// 迭代器起始位置
Iterator begin() const {
for (size_t i = 0; i < buckets.size(); ++i) {
if (buckets[i] != nullptr) {
return Iterator(buckets[i], buckets, i);
}
}
return end();
}
// 迭代器结束位置
Iterator end() const {
return Iterator(nullptr, buckets, buckets.size());
}
// 析构函数(释放内存)
~MyUnorderedMap() {
for (size_t i = 0; i < buckets.size(); ++i) {
Node* current = buckets[i];
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
}
};
经使用验证,均能实现基本操作。
5960



被折叠的 条评论
为什么被折叠?



