04. map 和 set 的使用
- [04. map 和 set 的使用](#04. map 和 set 的使用)
- [1. 阅读前问题卡:map 和 set](#1. 阅读前问题卡:map 和 set)
- [1.1 阅读前先看这几个问题](#1.1 阅读前先看这几个问题)
- [1.2 读完后完成这 3 道高频问题](#1.2 读完后完成这 3 道高频问题)
- [1.3 自检清单](#1.3 自检清单)
- [2. 序列式容器和关联式容器](#2. 序列式容器和关联式容器)
- [3. set 系列的使用](#3. set 系列的使用)
- [3.1 set 和 multiset 参考文档](#3.1 set 和 multiset 参考文档)
- [3.2 set 类的介绍](#3.2 set 类的介绍)
- [3.3 set 的构造和迭代器](#3.3 set 的构造和迭代器)
- [3.4 set 的增删查](#3.4 set 的增删查)
- [3.5 insert 和迭代器遍历使用样例](#3.5 insert 和迭代器遍历使用样例)
- [3.6 find 和 erase 使用样例](#3.6 find 和 erase 使用样例)
- [3.7 multiset 和 set 的差异](#3.7 multiset 和 set 的差异)
- [3.8 349. 两个数组的交集 - 力扣(LeetCode)](#3.8 349. 两个数组的交集 - 力扣(LeetCode))
- [3.9 142. 环形链表 II - 力扣(LeetCode)](#3.9 142. 环形链表 II - 力扣(LeetCode))
- [4. map 系列的使用](#4. map 系列的使用)
- [4.1 map 和 multimap 参考文档](#4.1 map 和 multimap 参考文档)
- [4.2 map 类的介绍](#4.2 map 类的介绍)
- [4.3 pair 类型介绍](#4.3 pair 类型介绍)
- [4.4 map 的构造](#4.4 map 的构造)
- [4.5 map 的增删查](#4.5 map 的增删查)
- [4.6 map 的数据修改](#4.6 map 的数据修改)
- [4.7 构造遍历及增删查使用样例](#4.7 构造遍历及增删查使用样例)
- [4.8 map 的迭代器和 \[\] 功能样例](#4.8 map 的迭代器和 [] 功能样例)
- [4.9 multimap 和 map 的差异](#4.9 multimap 和 map 的差异)
- [4.10 138. 随机链表的复制 - 力扣(LeetCode)](#4.10 138. 随机链表的复制 - 力扣(LeetCode))
- [4.11 692. 前 K 个高频单词 - 力扣(LeetCode)](#4.11 692. 前 K 个高频单词 - 力扣(LeetCode))
1. 阅读前问题卡:map 和 set
建议先读:第 2 节,先区分按位置访问和按关键字访问,再进入 set 和 map 的示例。
1.1 阅读前先看这几个问题
- 序列式容器按什么保存和访问元素?关联式容器又按什么保存和访问?
- 用
set插入重复值后,正向遍历会看到什么?改用greater<int>时,什么变了,什么没变? - 原文为什么对比算法库的
find和set::find?两者的查找复杂度分别是多少? - 区间删除示例中,
lower_bound(30)和upper_bound(60)各指向什么位置?为什么能删掉闭区间[30, 60]中的元素? - 向
map插入一个已有的 key,即使 value 不同,结果会如何?用find找到它后可以修改哪一部分? - 统计水果次数的两个示例里,第一次碰到某种水果和再次碰到它时,计数分别是怎么更新的?
- 复制随机链表时,
map的 key 和 value 分别是什么?这份映射在哪一轮被使用?
1.2 读完后完成这 3 道高频问题
1.2.1 高频问题 1:请说明 set 和 map 分别存储什么。它们的红黑树结构如何决定遍历顺序,又为什么能修改 map 的映射值,却不能通过迭代器修改关键字?
1.2.2 高频问题 2:map 的 operator[] 遇到已存在和不存在的 key 时分别会发生什么?请结合 insert 的返回值说明,两种情况下它如何得到可修改的映射值。
1.2.3 高频问题 3:与 set 和 map 相比,multiset 和 multimap 允许哪些重复?这会怎样影响按关键字执行的 count 和 erase?
1.3 自检清单
- 我能区分序列式容器按位置访问与关联式容器按关键字访问。
- 我能说明
set的去重规则,以及比较器对遍历顺序的影响。 - 我能解释
find返回end()的含义,并区分lower_bound与upper_bound对边界值的处理。 - 我能区分
map的mapped_type、节点存储的value_type和insert返回的pair。 - 我能用水果计数的例子解释
operator[]为什么可能插入新键。 - 我能解释高频单词示例中,为什么按频率做稳定排序能保留同频单词原来的字典序。
2. 序列式容器和关联式容器
前面我们已经接触过 STL 中的部分容器,如:string、vector、list、deque、array、forward_list 等。这些容器统称为序列式容器,因为逻辑结构为线性序列的数据结构,两个位置存储的值之间一般没有紧密的关联关系,比如交换一下,它依旧是序列式容器。顺序容器中的元素是按它们在容器中的存储位置来顺序保存和访问的。
关联式容器也是用来存储数据的。与序列式容器不同的是,关联式容器的逻辑结构通常是非线性结构,两个位置有紧密的关联关系,交换一下,它的存储结构就被破坏了。关联式容器中的元素是按关键字来保存和访问的。关联式容器有 map/set 系列和 unordered_map/unordered_set 系列。
本章节讲解的 map 和 set 底层是红黑树,红黑树是一棵平衡二叉搜索树。
set是 key 搜索场景的结构。map是 key/value 搜索场景的结构。
3. set 系列的使用
3.1 set 和 multiset 参考文档
https://legacy.cplusplus.com/reference/set/
3.2 set 类的介绍
set的声明如下,T就是set底层关键字的类型。set默认要求T支持小于比较。如果不支持,或者想按自己的需求走,可以自行实现仿函数传给第二个模板参数。set底层存储数据的内存是从空间配置器申请的。如果需要,可以自己实现内存池,传给第三个参数。- 一般情况下,我们都不需要传后两个模板参数。
set底层是用红黑树实现,增删查效率是O(logN),迭代器遍历走的是搜索树的中序,所以是有序的。- 前面部分我们已经学习了
vector/list等容器的使用,STL 容器接口设计高度相似,所以这里我们就不再一个接口一个接口地介绍,而是直接带着大家看文档,挑比较重要的接口进行介绍。
cpp
template <
class T, // set::key_type/value_type
class Compare = less<T>, // set::key_compare/value_compare
class Alloc = allocator<T> // set::allocator_type
> class set;
3.3 set 的构造和迭代器
set 的构造我们关注以下几个接口即可。
set 支持正向和反向迭代遍历。因为底层是二叉搜索树,迭代器遍历走的是中序,正向遍历默认按升序顺序。支持迭代器就意味着支持范围 for。set 的 iterator 和 const_iterator 都不支持通过迭代器修改数据,修改关键字数据会破坏底层搜索树的结构。
cpp
// empty (1) 无参默认构造
explicit set (const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
// range (2) 迭代器区间构造
template <class InputIterator>
set (InputIterator first, InputIterator last,
const key_compare& comp = key_compare(),
const allocator_type& = allocator_type());
// copy (3) 拷贝构造
set (const set& x);
// initializer list (5) initializer 列表构造
set (initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
// 迭代器是一个双向迭代器
// iterator -> a bidirectional iterator to const value_type
// 正向迭代器
iterator begin();
iterator end();
// 反向迭代器
reverse_iterator rbegin();
reverse_iterator rend();
3.4 set 的增删查
set 的增删查关注以下几个接口即可:
cpp
// Member types
// key_type -> The first template parameter (T)
// value_type -> The first template parameter (T)
// 单个数据插入,如果已经存在则插入失败
pair<iterator,bool> insert (const value_type& val);
// 列表插入,已经在容器中存在的值不会插入
void insert (initializer_list<value_type> il);
// 迭代器区间插入,已经在容器中存在的值不会插入
template <class InputIterator>
void insert (InputIterator first, InputIterator last);
// 查找val,返回val所在的迭代器,没有找到返回end()
iterator find (const value_type& val);
// 查找val,返回Val的个数
size_type count (const value_type& val) const;
// 删除一个迭代器位置的值
iterator erase (const_iterator position);
// 删除val,val不存在返回0,存在返回1
size_type erase (const value_type& val);
// 删除一段迭代器区间的值
iterator erase (const_iterator first, const_iterator last);
// 返回大于等val位置的迭代器
iterator lower_bound (const value_type& val) const;
// 返回大于val位置的迭代器
iterator upper_bound (const value_type& val) const;
3.5 insert 和迭代器遍历使用样例
cpp
#include<iostream>
#include<set>
using namespace std;
int main()
{
// 去重+升序排序
set<int> s;
// 去重+降序排序(给一个大于的仿函数)
//set<int, greater<int>> s;
s.insert(5);
s.insert(2);
s.insert(7);
s.insert(5);
//set<int>::iterator it = s.begin();
auto it = s.begin();
while (it != s.end())
{
// error C3892: "it": 不能给常量赋值
// *it = 1;
cout << *it << " ";
++it;
}
cout << endl;
// 插入一段initializer_list列表值,已经存在的值插入失败
s.insert({ 2,8,3,9 });
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
set<string> strset = { "sort", "insert", "add" };
// 遍历string比较ascll码大小顺序遍历的
for (auto& e : strset)
{
cout << e << " ";
}
cout << endl;
}
3.6 find 和 erase 使用样例
cpp
#include<iostream>
#include<set>
using namespace std;
int main()
{
set<int> s = { 4,2,7,2,8,5,9 };
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
// 删除最小值
s.erase(s.begin());
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
// 直接删除x
int x;
cin >> x;
int num = s.erase(x);
if (num == 0)
{
cout << x << "不存在!" << endl;
}
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
// 直接查找在利用迭代器删除x
cin >> x;
auto pos = s.find(x);
if (pos != s.end())
{
s.erase(pos);
}
else
{
cout << x << "不存在!" << endl;
}
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
// 算法库的查找 O(N)
auto pos1 = find(s.begin(), s.end(), x);
// set自身实现的查找 O(logN)
auto pos2 = s.find(x);
// 利用count间接实现快速查找
cin >> x;
if (s.count(x))
{
cout << x << "在!" << endl;
}
else
{
cout << x << "不存在!" << endl;
}
return 0;
}
cpp
#include<iostream>
#include<set>
using namespace std;
int main()
{
std::set<int> myset;
for (int i = 1; i < 10; i++)
myset.insert(i * 10); // 10 20 30 40 50 60 70 80 90
for (auto e : myset)
{
cout << e << " ";
}
cout << endl;
// 实现查找到的[itlow,itup)包含[30, 60]区间
// 返回 >= 30
auto itlow = myset.lower_bound(30);
// 返回 > 60
auto itup = myset.upper_bound(60);
// 删除这段区间的值
myset.erase(itlow, itup);
for (auto e : myset)
{
cout << e << " ";
}
cout << endl;
return 0;
}
3.7 multiset 和 set 的差异
multiset 和 set 的使用基本完全类似,主要区别点在于 multiset 支持值冗余,那么 insert、find、count、erase 都围绕着支持值冗余有所差异,具体参看下面的样例代码理解。
cpp
#include<iostream>
#include<set>
using namespace std;
int main()
{
// 相比set不同的是,multiset是排序,但是不去重
multiset<int> s = { 4,2,7,2,4,8,4,5,4,9 };
auto it = s.begin();
while (it != s.end())
{
cout << *it << " ";
++it;
}
cout << endl;
// 相比set不同的是,x可能会存在多个,find查找中序的第一个
int x;
cin >> x;
auto pos = s.find(x);
while (pos != s.end() && *pos == x)
{
cout << *pos << " ";
++pos;
}
cout << endl;
// 相比set不同的是,count会返回x的实际个数
cout << s.count(x) << endl;
// 相比set不同的是,erase给值时会删除所有的x
s.erase(x);
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
return 0;
}
3.8 349. 两个数组的交集 - 力扣(LeetCode)
cpp
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int> s1(nums1.begin(), nums1.end());
set<int> s2(nums2.begin(), nums2.end());
// 因为set遍历是有序的,有序值,依次比较
// 小的++,相等的就是交集
vector<int> ret;
auto it1 = s1.begin();
auto it2 = s2.begin();
while(it1 != s1.end() && it2 != s2.end())
{
if(*it1 < *it2)
{
it1++;
}
else if(*it1 > *it2)
{
it2++;
}
else
{
ret.push_back(*it1);
it1++;
it2++;
}
}
return ret;
}
};
3.9 142. 环形链表 II - 力扣(LeetCode)
数据结构初阶阶段,我们通过证明一个指针从头开始走、一个指针从相遇点开始走,会在入口点相遇,理解证明都会很麻烦。这里我们使用 set 查找记录,解决起来非常简单方便。这里体现了 set 在解决一些问题时的价值,完全是降维打击。
cpp
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
set<ListNode*> s;
ListNode* cur = head;
while(cur)
{
auto ret = s.insert(cur);
if(ret.second == false)
return cur;
cur = cur->next;
}
return nullptr;
}
};
4. map 系列的使用
4.1 map 和 multimap 参考文档
https://legacy.cplusplus.com/reference/map/
4.2 map 类的介绍
map 的声明如下:Key 就是 map 底层关键字的类型,T 是 map 底层 value 的类型。默认要求 Key 支持小于比较,如果不支持或者有需要,可以自行实现仿函数传给比较器模板参数。map 底层存储数据的内存是从空间配置器申请的。一般情况下,我们都不需要传后两个模板参数。
map 底层是用红黑树实现,增删查改效率是 O(logN),迭代器遍历走的是中序,所以是按 key 有序遍历的。
cpp
template <
class Key, // map::key_type
class T, // map::mapped_type
class Compare = less<Key>, // map::key_compare
class Alloc = allocator<pair<const Key,T> > // map::allocator_type
> class map;
4.3 pair 类型介绍
map 底层的红黑树节点中的数据,使用 pair 存储键值对数据。
cpp
typedef pair<const Key, T> value_type;
template <class T1, class T2>
struct pair
{
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair(): first(T1()), second(T2())
{}
pair(const T1& a, const T2& b): first(a), second(b)
{}
template<class U, class V>
pair (const pair<U,V>& pr): first(pr.first), second(pr.second)
{}
};
template <class T1,class T2>
inline pair<T1,T2> make_pair (T1 x, T2 y)
{
return ( pair<T1,T2>(x,y) );
}
4.4 map 的构造
map 的构造我们关注以下几个接口即可。
map 支持正向和反向迭代遍历。因为底层是二叉搜索树,迭代器遍历走的是中序,正向遍历默认按 key 的升序顺序。支持迭代器就意味着支持范围 for。map 支持修改 value,不支持修改 key,修改关键字数据会破坏底层搜索树的结构。
cpp
// empty (1) 无参默认构造
explicit map (const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
// range (2) 迭代器区间构造
template <class InputIterator>
map (InputIterator first, InputIterator last,
const key_compare& comp = key_compare(),
const allocator_type& = allocator_type());
// copy (3) 拷贝构造
map (const map& x);
// initializer list (5) initializer 列表构造
map (initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
// 迭代器是一个双向迭代器
// iterator -> a bidirectional iterator to const value_type
// 正向迭代器
iterator begin();
iterator end();
// 反向迭代器
reverse_iterator rbegin();
reverse_iterator rend();
4.5 map 的增删查
map 的增删查关注以下几个接口即可:
map的增加接口插入的是pair键值对数据,跟set有所不同。- 查和删的接口只用关键字 key,跟
set完全类似。不过find返回iterator,不仅可以确认 key 在不在,还能找到该 key 映射的 value,同时还可以通过迭代器修改 value。
cpp
// Member types
// key_type -> The first template parameter (Key)
// mapped_type -> The second template parameter (T)
// value_type -> pair<const key_type,mapped_type>
// 单个数据插入,如果已经key存在则插入失败,key存在相等value不相等也会插入失败
pair<iterator,bool> insert (const value_type& val);
// 列表插入,已经在容器中存在的值不会插入
void insert (initializer_list<value_type> il);
// 迭代器区间插入,已经在容器中存在的值不会插入
template <class InputIterator>
void insert (InputIterator first, InputIterator last);
// 查找k,返回k所在的迭代器,没有找到返回end()
iterator find (const key_type& k);
// 查找k,返回k的个数
size_type count (const key_type& k) const;
// 删除一个迭代器位置的值
iterator erase (const_iterator position);
// 删除k,k存在返回0,存在返回1
size_type erase (const key_type& k);
// 删除一段迭代器区间的值
iterator erase (const_iterator first, const_iterator last);
// 返回大于等k位置的迭代器
iterator lower_bound (const key_type& k);
// 返回大于k位置的迭代器
const_iterator lower_bound (const key_type& k) const;
4.6 map 的数据修改
前面提到,map 支持修改 mapped_type 数据,不支持修改 key。修改关键字数据会破坏底层搜索树的结构。
- 第一种修改方式是通过迭代器,可以在迭代器遍历时修改,也可以通过
find返回的指向 key 所在节点的iterator修改。 map还有一个非常重要的修改接口operator[]。这个接口不仅支持修改,还支持插入和查找数据,所以是一个多功能复合接口。
需要注意的是,从内部实现角度看:
mapped_type:传统所说的 value,类型是T,日常使用中还是习惯将这个映射值叫作 value。value_type:红黑树节点中存储的pair键值对。
cpp
// Member types
// key_type -> The first template parameter (Key)
// mapped_type -> The second template parameter (T)
// value_type -> pair<const key_type,mapped_type>
// 查找k,返回k所在的迭代器,没有找到返回end(),如果找到了通过iterator可以修改key对应的
// mapped_type值
iterator find (const key_type& k);
// 文档中对insert返回值的说明
// The single element versions (1) return a pair, with its member pair::first
// set to an iterator pointing to either the newly inserted element or to the
// element with an equivalent key in the map. The pair::second element in the pair
// is set to true if a new element was inserted or false if an equivalent key
// already existed.
// insert插入一个pair<key, T>对象
// 1、如果key已经在map中,插入失败,则返回一个pair<iterator,bool>对象,返回pair对象
// first是key所在结点的迭代器,second是false
// 2、如果key不在在map中,插入成功,则返回一个pair<iterator,bool>对象,返回pair对象
// first是新插入key所在结点的迭代器,second是true
// 也就是说无论插入成功还是失败,返回pair<iterator,bool>对象的first都会指向key所在的迭代器
// 那么也就意味着insert插入失败时充当了查找的功能,正是因为这一点,insert可以用来实现operator[]
// 需要注意的是这里有两个pair,不要混淆了,一个是map底层红黑树节点中存的pair<key, T>,
// 另一个是insert返回值pair<iterator,bool>
pair<iterator,bool> insert (const value_type& val);
mapped_type& operator[] (const key_type& k);
// operator的内部实现
mapped_type& operator[] (const key_type& k)
{
// 1、如果k不在map中,insert会插入k和mapped_type默认值,同时[]返回结点中存储
// mapped_type值的引用,那么我们可以通过引用修改返映射值。所以[]具备了插入+修改功能
// 2、如果k在map中,insert会插入失败,但是insert返回pair对象的first是指向key结点的
// 迭代器,返回值同时[]返回结点中存储mapped_type值的引用,所以[]具备了查找+修改的功能
pair<iterator, bool> ret = insert({ k, mapped_type() });
iterator it = ret.first;
return it->second;
}
4.7 构造遍历及增删查使用样例
cpp
#include<iostream>
#include<map>
using namespace std;
int main()
{
// initializer_list构造及迭代遍历
map<string, string> dict = { {"left", "左边"}, {"right", "右边"},
{"insert", "插入"},{ "string", "字符串" } };
//map<string, string>::iterator it = dict.begin();
auto it = dict.begin();
while (it != dict.end())
{
//cout << (*it).first <<":"<<(*it).second << endl;
// map的迭代基本都使用operator->,这里省略了一个->
// 第一个->是迭代器运算符重载,返回pair*,第二个箭头是结构指针解引用取
// pair数据
//cout << it.operator->()->first << ":" << it.operator->()->second << endl;
cout << it->first << ":" << it->second << endl;
++it;
}
cout << endl;
// insert插入pair对象的4种方式,对比之下,最后一种最方便
pair<string, string> kv1("first", "第一个");
dict.insert(kv1);
dict.insert(pair<string, string>("second", "第二个"));
dict.insert(make_pair("sort", "排序"));
dict.insert({ "auto", "自动的" });
// "left"已经存在,插入失败
dict.insert({ "left", "左边,剩余" });
// 范围for遍历
for (const auto& e : dict)
{
cout << e.first << ":" << e.second << endl;
}
cout << endl;
string str;
while (cin >> str)
{
auto ret = dict.find(str);
if (ret != dict.end())
{
cout << "->" << ret->second << endl;
}
else
{
cout << "无此单词,请重新输入" << endl;
}
}
// erase等接口跟set完全类似,这里就不演示讲解了
return 0;
}
4.8 map 的迭代器和 \[\] 功能样例
cpp
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
// 利用find和iterator修改功能,统计水果出现的次数
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
"苹果", "香蕉", "苹果", "香蕉" };
map<string, int> countMap;
for (const auto& str : arr)
{
// 先查找水果在不在map中
// 1、不在,说明水果第一次出现,则插入{水果, 1}
// 2、在,则查找到的节点中水果对应的次数++
auto ret = countMap.find(str);
if (ret == countMap.end())
{
countMap.insert({ str, 1 });
}
else
{
ret->second++;
}
}
for (const auto& e : countMap)
{
cout << e.first << ":" << e.second << endl;
}
cout << endl;
return 0;
}
cpp
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
// 利用[]插入+修改功能,巧妙实现统计水果出现的次数
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
"苹果", "香蕉", "苹果", "香蕉" };
map<string, int> countMap;
for (const auto& str : arr)
{
// []先查找水果在不在map中
// 1、不在,说明水果第一次出现,则插入{水果, 0},同时返回次数的引用,
// ++一下就变成1次了
// 2、在,则返回水果对应的次数++
countMap[str]++;
}
for (const auto& e : countMap)
{
cout << e.first << ":" << e.second << endl;
}
cout << endl;
return 0;
}
cpp
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
map<string, string> dict;
dict.insert(make_pair("sort", "排序"));
// key不存在->插入 {"insert", string()}
dict["insert"];
// 插入+修改
dict["left"] = "左边";
// 修改
dict["left"] = "左边、剩余";
// key存在->查找
cout << dict["left"] << endl;
return 0;
}
4.9 multimap 和 map 的差异
multimap 和 map 的使用基本完全类似,主要区别点在于 multimap 支持关键字 key 冗余,那么 insert、find、count、erase 都围绕着支持 key 冗余有所差异。这跟 set 和 multiset 完全一样,比如 find 时有多个 key,返回中序第一个。
其次就是 multimap 不支持 [],因为支持 key 冗余,[] 就只能支持插入,不能支持修改。
4.10 138. 随机链表的复制 - 力扣(LeetCode)
数据结构初阶阶段,为了控制随机指针,我们将拷贝结点链接在原节点的后面解决,后面拷贝节点还得解下来链接,非常麻烦。这里我们直接将 {原结点,拷贝结点} 的映射关系放到 map 中,控制随机指针会非常简单方便。这里体现了 map 在解决一些问题时的价值,完全是降维打击。
cpp
class Solution {
public:
Node* copyRandomList(Node* head) {
map<Node*, Node*> nodeMap;
Node* copyhead = nullptr,*copytail = nullptr;
Node* cur = head;
while(cur)
{
if(copytail == nullptr)
{
copyhead = copytail = new Node(cur->val);
}
else
{
copytail->next = new Node(cur->val);
copytail = copytail->next;
}
// 原节点和拷贝节点map kv存储
nodeMap[cur] = copytail;
cur = cur->next;
}
// 处理random
cur = head;
Node* copy = copyhead;
while(cur)
{
if(cur->random == nullptr)
{
copy->random = nullptr;
}
else
{
copy->random = nodeMap[cur->random];
}
cur = cur->next;
copy = copy->next;
}
return copyhead;
}
};
4.11 692. 前 K 个高频单词 - 力扣(LeetCode)
本题目我们利用 map 统计出次数以后,返回的答案应该按单词出现频率由高到低排序。有一个特殊要求:如果不同的单词有相同出现频率,按字典顺序排序。
解决思路 1:
用排序找前 k 个单词。因为 map 中已经对 key(单词)排序过,也就意味着遍历 map 时,次数相同的单词,字典序小的在前面,字典序大的在后面。那么我们将数据放到 vector 中用一个稳定的排序就可以实现上面特殊要求。但是 sort 底层是快排,是不稳定的,所以我们要用稳定的 stable_sort。
cpp
class Solution {
public:
struct Compare
{
bool operator()(const pair<string, int>& x, const pair<string, int>& y) const
{
return x.second > y.second;
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> countMap;
for(auto& e : words)
{
countMap[e]++;
}
vector<pair<string, int>> v(countMap.begin(), countMap.end());
// 仿函数控制降序
stable_sort(v.begin(), v.end(), Compare());
//sort(v.begin(), v.end(), Compare());
// 取前k个
vector<string> strV;
for(int i = 0; i < k; ++i)
{
strV.push_back(v[i].first);
}
return strV;
}
};
解决思路 2:
将 map 统计出的次数数据放到 vector 中排序,或者放到 priority_queue 中来选出前 k 个。利用仿函数控制次数相等时,字典序小的在前面。
cpp
class Solution {
public:
struct Compare
{
bool operator()(const pair<string, int>& x, const pair<string, int>& y) const
{
return x.second > y.second || (x.second == y.second && x.first < y.first);;
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> countMap;
for(auto& e : words)
{
countMap[e]++;
}
vector<pair<string, int>> v(countMap.begin(), countMap.end());
// 仿函数控制降序,仿函数控制次数相等,字典序小的在前面
sort(v.begin(), v.end(), Compare());
// 取前k个
vector<string> strV;
for(int i = 0; i < k; ++i)
{
strV.push_back(v[i].first);
}
return strV;
}
};
cpp
class Solution {
public:
struct Compare
{
bool operator()(const pair<string, int>& x, const pair<string, int>& y) const
{
// 要注意优先级队列底层是反的,大堆要实现小于比较,所以这里次数相等,想要字典序小的在前面要比较字典序大的为真
return x.second < y.second || (x.second == y.second && x.first > y.first);
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> countMap;
for(auto& e : words)
{
countMap[e]++;
}
// 将map中的<单词,次数>放到priority_queue中,仿函数控制大堆,次数相同按照字典序规则排序
priority_queue<pair<string, int>, vector<pair<string, int>>, Compare>
p(countMap.begin(), countMap.end());
vector<string> strV;
for(int i = 0; i < k; ++i)
{
strV.push_back(p.top().first);
p.pop();
}
return strV;
}
};
5.回答问题卡的问题
问题 1:序列式容器按什么保存和访问元素?关联式容器又按什么保存和访问?
答:
顺序容器中的元素是按它们在容器中的存储位置来顺序保存和访问的。
关联式容器中的元素是按关键字来保存和访问的。
问题 2:用 set 插入重复值后,正向遍历会看到什么?改用 greater<int> 时,什么变了,什么没变?
答:
std::set 的本质是有序且去重的容器 。插入重复元素时,不会再插入一份相同的值,单元素的 insert 返回的 pair 中,second 会是 false,表示没有插入,重复本身也不会引发异常。因此正向遍历时,每个值只出现一次,默认按照升序排列。比如依次插入 5、2、7、5,遍历出来的是 2、5、7。
正向遍历的具体顺序。默认从小到大,改用 greater<int> 后从大到小;元素类型和去重规则都没有改变。
问题 3:原文为什么对比算法库的 find 和 set::find?两者的查找复杂度分别是多少?
答:
因为两者的底层算法逻辑,数据结构不一样,算法库的 find 在迭代器区间内逐个查找,而 set::find 可以根据红黑树的搜索结构缩小查找范围。
算法库的查找 O(N);set自身实现的查找 O(logN)
问题 4:区间删除示例中,lower_bound(30) 和 upper_bound(60) 各指向什么位置?为什么能删掉闭区间 [30, 60] 中的元素?
答:
lower_bound(30) 返回第一个大于或等于 30 的元素的迭代器 itlow,在这个例子里指向 30。upper_bound(60) 返回第一个大于 60 的元素的迭代器 itup,也就是指向 70。
这样查找到的半开区间 [itlow, itup) 正好包含闭区间 [30, 60] 中的所有元素。erase(itlow, itup) 包含起点、不包含终点,所以删掉的是 30、40、50、60,70 会保留下来。
问题 5:向 map 插入一个已有的 key,即使 value 不同,结果会如何?用 find 找到它后可以修改哪一部分?
答:
不支持修改 key,修改关键字数据会破坏底层搜索树的结构。如果已经key存在则插入失败,key存在相等value不相等也会插入失败
find 返回 iterator,不仅可以确认 key 在不在,还能找到该 key 映射的 value,同时还可以通过迭代器修改 value。
问题 6:统计水果次数的两个示例里,第一次碰到某种水果和再次碰到它时,计数分别是怎么更新的?
答:
第一个中查找水果在不在map中,不在,说明水果第一次出现,则插入{水果, 1};在,则查找到的节点中水果对应的次数++
第二个利用\[\]插入+修改功能,巧妙实现统计水果出现的次数, \[\]先查找水果在不在map中,不在,说明水果第一次出现,则插入{水果, 0},同时返回次数的引用,++一下就变成1次了;在,则返回水果对应的次数++
问题 7:复制随机链表时,map 的 key 和 value 分别是什么?这份映射在哪一轮被使用?
答:
key是原结点,value是拷贝结点
在第一轮进行链表复制时,建立原结点和拷贝结点的一一对应关系,并连接好拷贝链表的 next 指针。
第二轮处理 random 指针时才用到这份映射。原结点的 random 指向哪个原结点,就把这个原结点的指针当作 key,到 map 中找到对应的拷贝结点,让当前拷贝结点的 random 指向它;如果原来的 random 是空指针,拷贝出来的也设为空。
高频问题 1:请说明 set 和 map 分别存储什么。它们的红黑树结构如何决定遍历顺序,又为什么能修改 map 的映射值,却不能通过迭代器修改关键字?
答:
set 存储的是关键字本身;map 存储的是 key 和 value 组成的键值对,节点里保存的是 pair<const Key, T>。
它们通常都用红黑树来实现。红黑树是一棵平衡二叉搜索树,节点按照关键字比较的结果来组织,迭代器按照搜索树的中序顺序遍历。所以在使用默认比较器时,set 正向遍历按元素升序,map 正向遍历按 key 升序。
map 可以通过普通迭代器修改 value,因为 value 不参与树的排序。key 决定了节点在树中的位置,如果直接修改 key,就可能破坏搜索树原来的顺序,导致查找不正确。因此节点的 key 是 const,而映射值可以修改。
set 中的元素本身就是 key,所以也不能通过迭代器直接修改元素。
高频问题 2:map 的 operator[] 遇到已存在和不存在的 key 时分别会发生什么?请结合 insert 的返回值说明,两种情况下它如何得到可修改的映射值。
答:
如果 key 已经存在,operator[] 就返回已有映射值的引用;如果 key 不存在,就先插入这个 key 和默认构造出来的映射值,再返回新映射值的引用。有了引用,就能直接修改节点里存储的 value。
可以结合单元素 insert 的返回值来理解这个过程。它返回的是 pair<iterator, bool>:
- key 已存在时,插入失败,
second是 false,first指向已经存在的节点。 - key 不存在时,插入成功,
second是 true,first指向刚插入的节点。
所以原文的示意实现可以直接利用 insert({k, mapped_type()}) 得到返回值 ret。无论插入是否成功,ret.first 都指向这个 key 所在的节点,返回 ret.first->second 的引用就能得到可修改的映射值。
高频问题 3:与 set 和 map 相比,multiset 和 multimap 允许哪些重复?这会怎样影响按关键字执行的 count 和 erase?
答:
set 和 map 都不允许重复的关键字。multiset 允许存储重复的元素,multimap 允许多个键值对拥有相同的 key,这些键值对的 value 可以相同,也可以不同。
所以按关键字 count 时,set 和 map 只能返回 0 或 1,而 multiset 和 multimap 会返回该关键字实际出现的次数,可能大于 1。
按关键字 erase 时,set 和 map 最多只能删除一个元素;multiset 和 multimap 会把所有匹配该关键字的元素都删掉,返回删除的元素个数。如果只想删除其中一个,可以使用指向该元素的迭代器来删除。