杀鸡焉用牛刀 发表于 2024-11-19 09:58:59

【C++】—— map 与 set 深入浅出:设计原理与应用对比

https://i-blog.csdnimg.cn/direct/a2ce3e82f40d4ac3b67be011e85d8d3e.gif
不要只因一次失败,就放弃你原来刻意想到达的目的。
—— 莎士比亚
目次
1、序列式容器与关联式容器的概述与比较
2、set 与 multiset
2.1 性质分析:唯一性与多重性的差别
2.2 接口解析:功能与操作的全面解读
3、map 与 multimap
3.1 性质分析:键值对的唯一性与多重性
​编辑3.2 接口解析:常用操作与实现细节
multimap 与 map 接口差别
4、OJ应用
349. 两个数组的交集 - 力扣(LeetCode)
LCR 022. 环形链表 II - 力扣(LeetCode)
138. 随机链表的复制 - 力扣(LeetCode)
​​​​​​​​692. 前K个⾼频单词 - 力扣(LeetCode)
Thanks 谢谢阅读!
1、序列式容器与关联式容器的概述与比较

   之前的学习之中 , 我们已经接触过STL中的部分容器,比如:vector、list、deque、forward_list(C++11)等,这些容器统称为序列式容器,由于其底层为线性序列的数据结构,里面存储的是元素本身。两个位置存储的值之间⼀般没有紧密的关联关系,比如如交换⼀下,他依旧是序列式容器。次序容器中的元素是按他们在容器中的存储位置来次序保存和访问的。
而 map 与 set 是关联性容器 , 那什么是关联式容器?它与序列式容器有什么区别?关联式容器也是用来存储数据的,和序列式容器不同的是,其里面存储的是 <key, value>结构的键值对,在数据检索时比序列式容器服从更高!
关联式容器逻辑结构通常是非线性结构,两个位置有紧密的关联关系,交换⼀下,他的存储结构就被破坏了。关联式中的元素是按关键字来保存和访问的。关联式容器有 map/set 系列和unordered_map/unordered_set 系列。
键值对是一个紧张的概念!!!
键值对用来表示具有逐一对应关系的一种结构,该结构中一般只包含两个成员变量key和value,key代表键值,value表示与key对应的信息。
   比如:现在要建立一个英汉互译的字典,那该字典中必然有英文单词与其对应的中文含义,而且,英文单词与其中文含义是逐一对应的关系,即通过该应该单词,在辞书中就可以找到与其对应的中文含义。
就是类似映射关系,通过键值 key可以找到对应的 value
2、set 与 multiset

2.1 性质分析:唯一性与多重性的差别

set - C++ Reference  
https://i-blog.csdnimg.cn/direct/eba3e8500f334faf91b3ff6e7e8af853.png
   
[*]set是按照肯定序次存储元素的容器
[*]在set中,元素的value也表示它(value就是key,类型为T),并且每个value必须是唯一(unique)的。set中的元素不能在容器中修改(元素总是const),但是可以从容器中插入或删除它们。
[*]在内部,set中的元素总是按照其内部比较对象(类型比较)所指示的特定严格弱排序准则举行排序。
[*]set容器通过key访问单个元素的速度通常比 unordered_set容器慢,但它们答应根据次序对子集举行直接迭代。
[*]set在底层是用二叉搜刮树(红黑树)实现的
set的声明如下,T就是set底层关键字的类型
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;
• set默认要求T支持小于比较,如果不支持大概想自己的需求来可以自行实现仿函数传给第二个模
版参数
• set底层存储数据的内存是从空间配置器申请的,如果必要可以自己实现内存池,传给第三个参
数。
• ⼀般情况下,我们都不必要传后两个模版参数。
• set底层是用红黑树实现,增删查服从 Log N ,迭代器遍历是走的搜刮树的中序,所以是有序

2.2 接口解析:功能与操作的全面解读



[*]构造函数
https://i-blog.csdnimg.cn/direct/a88ef7db19784861b49ecfdc53da6e2e.png
我们一般必要提供T键值,Compare 仿函数默认是按升序排,有需求可以自行传入!!!Alloc是set中元素空间的管理方式,使用STL提供的空间配置器管理。所以一般我们不必要传递后两个参数。
// 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(); 与之前的容器大差不差,不再细说。


[*]增删查
set是不答应修改的,修改会破坏其BST的结构特征。
焦点接口:

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; 这里 key/value都是 T,set 本身并不必要value 这样设计为了和 map 保持同等性
https://i-blog.csdnimg.cn/direct/f5cc53b83b2f4a8482efd488575981e7.png
insert 
https://i-blog.csdnimg.cn/direct/31181406fb64465fb634129fdc218f8d.png

intmain()
{
        // 去重+升序排序
        set<int> s; // less 小的为真 到搜素树根左边去 greater时候 大的为真 到左边去
        // 去重+降序排序(给⼀个⼤于的仿函数)
        //set<int, greater<int>> s;
        s.insert(5);
        s.insert(2);
        s.insert(7);
        s.insert(5);

        // 插⼊⼀段initializer_list列表值,已经存在的值插⼊失败 //底层相当于一个一个调用 insert
        set<int>::iterator it = s.begin();
        while (it != s.end())
        {
                // error C3892: “it”: 不能给常量赋值
                // *it = 1;
                cout << *it << ' ';
                it++;
        }
        cout << endl;

        s.insert({ 2,8,3,9 });
        for (auto e : s)
        {
                cout << e << " ";
        }
        cout << endl;

        //void insert(initializer_list<value_type> il); 隐式类型转换了
        set<string>ss = { "sort", "insert", "add" };

        //set<string>ss = ( "sort", "insert", "add" ); 显示传 il
       
        // 遍历string⽐较ascll码⼤⼩顺序遍历的
        for (auto e : ss)
        {
                cout << e << ' ';
        }
        cout << endl;

        return 0;
} find 与 erase
https://i-blog.csdnimg.cn/direct/c878746533df4ba9b15ad8a8def1aa03.png
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 迭代器失效 1.删除叶子节点 野指针 2.删除根 换根失去原有意义 vs访问直接保持
        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)) // count 返回元素个数
        {
                cout << x << "在!" << endl;
        }
        else
        {
                cout << x << "不在!" << endl;
        }
        return 0;
}  关于区间的删除
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;

        // 1.删除 值
        // 2.删除 值

       实现查找到的区间
       返回 >= 30
        //auto itlow = myset.lower_bound(30);
       返回 > 50
        //auto itup = myset.upper_bound(50);
       
        //返回 >=25
        auto itlow = myset.lower_bound(25); //左闭
        //返回 >55
        auto itup = myset.upper_bound(55); //右开
        myset.erase(itlow, itup);
        for (auto e : myset)
        {
                cout << e << " ";
        }
        cout << endl;
        return 0;
}  multiset 与 set 接口差别
#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;

        //pos = s.find(x);
        //while (pos != s.end() && *pos == x)
        //{
        //        pos = s.erase(pos); //erase 传迭代器会返回下一个位置迭代器
        //}
        //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、map 与 multimap

3.1 性质分析:键值对的唯一性与多重性

map - C++ Reference
https://i-blog.csdnimg.cn/direct/b6f1526faea145958747e8acbe25e4fd.png
   
[*]map是关联容器,它按照特定的序次(按照key来比较)存储由键值key和值value组合而成的元素。
[*]在map中,键值key通常用于排序和惟一地标识元素,而值value中存储与此键值key关联的内容。键值key和值value的类型可能不同,并且在map的内部,key与value通过成员类型value_type绑定在一起,为其取别名称为pair:typedef pair<const key, T> value_type;
[*]在内部,map中的元素总是按照键值key举行比较排序的。
[*]map中通过键值访问单个元素的速度通常比unordered_map容器慢,但map答应根据次序对元素举行直接迭代(即对map中的元素举行迭代时,可以得到一个有序的序列)。
[*]map支持下标访问符,即在[ ]中放入key,就可以找到与key对应的value。
[*]map通常被实现为二叉搜刮树(更正确的说:平衡二叉搜刮树(红黑树))。
map的声明如下,Key就是map底层关键字的类型,T是map底层value的类型
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; •map默认要求Key支持小于比较,如果不支持大概想自己的需求来可以自行实现仿函数传给第三个模版参数
• map底层存储数据的内存是从空间配置器申请的,如果必要可以自己实现内存池,传给第个参
数。
• ⼀般情况下,我们都不必要传后两个模版参数。
• map底层是用红黑树实现,增删查服从 Log N ,迭代器遍历是走的搜刮树的中序,所以是按照key有序遍历的
pair 类型介绍
map底层的红黑树节点中的数据,使用 pair<Key,T> 存储键值对数据。
// map 底层 value_type 原型解释
typedef pair<const Key, T> value_type;

// pair 原型
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));
} https://i-blog.csdnimg.cn/direct/f6cb292035764e2585b116a90001f4c7.png3.2 接口解析:常用操作与实现细节



[*]构造函数
https://i-blog.csdnimg.cn/direct/2078b377dbf1428082a54a308304a613.png
key:键值对中key的类型
T: 键值对中value的类型
Compare: 比较器的类型,map中的元素是按照key来比较的,缺省情况下按照小于来比较,一般情况下(内置类型元素)该参数不必要传递,如果无法比较时(自定义类型),必要用户自己显式传递比较规则(一般情况下按照函数指针大概仿函数来传递)
Alloc:通过空间配置器来申请底层空间,不必要用户传递,除非用户不想使用标准库提供的空间配置器
// 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();

[*]增删查
焦点接口:
   map 增接口,插入的pair 键值对数据,跟 set 所有不同,但是查和删的接口只用关键字key跟set是完全类似的,不外 find 返回iterator,不但仅可以确认key在不在,还找到key映射的value,同时通过迭代还可以修改value

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;
map的删除查找与set 完全类似,不再赘述用例
#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())
        {
                //(*it).first += "xxx"; 不可以更改 key 可以更改value
                (*it).second += "xxx";

                //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;
                }
        }
       
        return 0;
}

[*]map数据的修改 [ ]
map支持修改mapped_type 数据,不支持修改key数据,由于修改关键字数据,破坏了底层搜刮树的结构。
map第一个支持修改的方式是通过迭代器,迭代器遍历时大概 find 返回 key 所在的 iterator 修 map
另有一个非常紧张的修改接口 operator[ ] ,但是operator[ ]不但仅支持修改,还支持插入数据和查找数据,所以他是⼀个多功能复合接口,必要注意从内部实现的角度,map这里把我们传统说的value值,给的是T类型,typedef为mapped_type。而value_type是红黑树结点中存储的pair键值对值。一样平常使用我们还是风俗将这里的T映射值叫做value。
 
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;
} [ ]用例:
int main()
{
       
        string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
        "苹果", "香蕉", "苹果", "香蕉" };
        map<string, int> countMap;
        for (const auto& str : arr)
        {
                // 利⽤find和iterator修改功能,统计⽔果出现的次数
               先查找⽔果在不在map中
               1、不在,说明⽔果第⼀次出现,则插⼊{⽔果, 1}
               2、在,则查找到的节点中⽔果对应的次数++
               
                //auto ret = countMap.find(str);
                //if (ret == countMap.end())
                //{
                //        countMap.insert({ str, 1 });
                //}
                //else
                //{
                //ret->second++;
                //}

                //利用 []的插入+查找+修改
               
                //[]先查找⽔果在不在map中
                // 1、不在,说明⽔果第⼀次出现,则插⼊{⽔果, 0},同时返回次数的引⽤,
                //++⼀下就变成1次了
                // 2、在,则返回⽔果对应的次数++
                countMap++;
        }

        for (const auto & e : countMap)
                {
                        cout << e.first << ":" << e.second << endl;
                }
                cout << endl;
               

                map<string, string> dict;
                dict.insert(make_pair("sort", "排序"));
                // key不存在->插⼊ {"insert", string()}
                dict["insert"];
                // 插⼊+修改
                dict["left"] = "左边";
                // 修改
                dict["left"] = "左边、剩余";
                // key存在->查找
                cout << dict["left"] << endl;
                // key不存在->插入所以查找得确定 key存在情况下 否则可能为插入
                cout << dict["right"] << endl;

                for (const auto& e : dict)
                {
                        cout << e.first << ":" << e.second << endl;
                }
                cout << endl;
       

                return 0;
} multimap 与 map 接口差别

multimap和map的使用根本完全类似,主要区别点在于multimap 支持关键值key冗余,那么
insert/find/count/erase 都围绕着支持关键值key冗余有所差别,这里跟set和multiset 完全⼀样
比如 find 时,有多个key,返回中序第⼀个。其次就是multimap不再支持[ ],由于支持 key 冗余
[ ]就只能支持插⼊了,不能支持修改。
 
4、OJ应用

349. 两个数组的交集 - 力扣(LeetCode)

https://i-blog.csdnimg.cn/direct/1e21491cc3014630b4523988d4bc60b2.png​
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;
    }
}; 分析:
set 去重+有序 双指针找交集
https://i-blog.csdnimg.cn/direct/12c1eb8f03e348c5a87fbd20aa34850e.png
思考: 找差集呢? 双指针该如何操作?
https://i-blog.csdnimg.cn/direct/ca9e0ec7333e4ab39346e397381ecea3.png
小的就是差集,由于有序另一序列不可能比这个还小了
LCR 022. 环形链表 II - 力扣(LeetCode)

https://i-blog.csdnimg.cn/direct/9c18779847f648dd9e22f0c1cf1bcde7.png​
我们可以用快慢双指针的方法办理这个题目,但是这里为了兼容set,实行使用set办理,使用set 唯一性办理环形链表交点题目
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;*/
            
                        if (s.count(cur))
                                return cur;
                        s.insert(cur);
                        cur = cur->next;
                }
                return nullptr;
        }
}; https://i-blog.csdnimg.cn/direct/64776843dc1847519943bdec7b41da10.png
138. 随机链表的复制 - 力扣(LeetCode)

https://i-blog.csdnimg.cn/direct/bd48520b72fd44debf40fb7818129239.png​
https://i-blog.csdnimg.cn/direct/371a7a7e82d24dd3a9b67b5089e0f522.png
/*
// 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) {
      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;
            }
            // 建立映射关系
            nodeMap=copytail;
            cur=cur->next;
      }
      // 随机指针的复制
      cur=head;
      Node*copycur=copyhead;
      while(cur)
      {
            if(cur->random==nullptr)
            {
                copycur->random=nullptr;
            }   
            else
            {
                copycur->random=nodeMap;
            }
            cur=cur->next;
            copycur=copycur->next;
      }
      return copyhead;
    }
};

​​​​​​​​​​​​​​​​​​​​​​692. 前K个⾼频单词 - 力扣(LeetCode)

https://i-blog.csdnimg.cn/direct/6d57e6c9416a455b9d868fb284ba04fe.png
map 直接是可以字典序排序的,同时映射关系可以反应数量

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++;
      }
      vector<pair<string, int>> v(countMap.begin(), countMap.end());

      // 仿函数控制降序 稳定排序 这里自定义仿函数因为 我们只需要比较 pair.second
      stable_sort(v.begin(), v.end(), Compare());
      //sort(v.begin(), v.end(), Compare());
      vector<string>ret;
      for(int i=0;i<k;i++)
      {
            ret.push_back(v.first);
      }
      return ret;
    }

}; 这里使用了 stable_sort 究竟上也可以用 sort 但是我们必要控制比较逻辑 确保字典序 不被打扰
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++;
      }
      vector<pair<string, int>> v(countMap.begin(), countMap.end());
      // 仿函数控制降序,仿函数控制次数相等,字典序⼩的在前⾯
      sort(v.begin(), v.end(), Compare());
      // 取前k个
      vector<string>ret;
      for(int i=0;i<k;i++)
      {
            ret.push_back(v.first);
      }
      return ret;
    }
}; 优先级队列实现策略:
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++;
      }
      // 将map中的<单词,次数>
      // 放到priority_queue中,仿函数控制⼤堆,次数相同按照字典序规则排序
      priority_queue<pair<string, int>, vector<pair<string, int>>, Compare> p(
            countMap.begin(), countMap.end());
      vector<string> ret;
      for (int i = 0; i < k; ++i) {
            ret.push_back(p.top().first);
            p.pop();
      }
      return ret;
    }
}; 可以看到仿函数的功能很强盛,不外运用也得熟悉容器的底层框架,排序的逻辑
Thanks 谢谢阅读!


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 【C++】—— map 与 set 深入浅出:设计原理与应用对比