0


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

a2ce3e82f40d4ac3b67be011e85d8d3e.gif

不要只因一次失败,就放弃你原来决心想达到的目的。

—— 莎士比亚



1、序列式容器与关联式容器的概述与比较

之前的学习之中 , 我们已经接触过STL中的部分容器,比如:vector、list、deque、forward_list(C++11)等,这些容器统称为序列式容器,因为其底层为线性序列的数据结构,里面存储的是元素本身。两个位置存储的值之间⼀般没有紧密的关联关系,比如如交换⼀下,他依旧是序列式容器。顺序容器中的元素是按他们在容器中的存储位置来顺序保存和访问的。

而 map 与 set 是关联性容器 , 那什么是关联式容器?它与序列式容器有什么区别?关联式容器也是用来存储数据的,**和序列式容器不同的是,其里面存储的是

  1. <key, value>

结构的键值对**,在数据检索时比序列式容器效率更高!

关联式容器逻辑结构通常是非线性结构,两个位置有紧密的关联关系,交换⼀下,他的存储结构就被破坏了。关联式中的元素是按关键字来保存和访问的。关联式容器有 map/set 系列和unordered_map/unordered_set 系列。

键值对是一个重要的概念!!!

键值对用来表示具有一一对应关系的一种结构,该结构中一般只包含两个成员变量

  1. key

  1. value

  1. key

代表键值,

  1. value

表示与

  1. key

对应的信息。

比如:现在要建立一个英汉互译的字典,那该字典中必然有英文单词与其对应的中文含义,而且,英文单词与其中文含义是一一对应的关系,即通过该应该单词,在词典中就可以找到与其对应的中文含义。

**就是类似映射关系,通过键值

  1. key

可以找到对应的

  1. value

**

2、set 与 multiset

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

set - C++ Reference

eba3e8500f334faf91b3ff6e7e8af853.png

  1. set是按照一定次序存储元素的容器
  2. 在set中,元素的value也表示它(value就是key,类型为T),并且每个value必须是唯一(unique)的。set中的元素不能在容器中修改(元素总是const),但是可以从容器中插入或删除它们。
  3. 在内部,set中的元素总是按照其内部比较对象(类型比较)所指示的特定严格弱排序准则进行排序。
  4. set容器通过key访问单个元素的速度通常比 unordered_set容器慢,但它们允许根据顺序对子集进行直接迭代。
  5. set在底层是用二叉搜索树(红黑树)实现的

set的声明如下,T就是set底层关键字的类型

  1. template < class T, // set::key_type/value_type
  2. class Compare = less<T>, // set::key_compare/value_compare
  3. class Alloc = allocator<T> // set::allocator_type
  4. > class set;

• set默认要求T支持小于比较,如果不支持或者想自己的需求来可以自行实现仿函数传给第二个模
版参数

• set底层存储数据的内存是从空间配置器申请的,如果需要可以自己实现内存池,传给第三个参
数。
• ⼀般情况下,我们都不需要传后两个模版参数。
• set底层是用红黑树实现,增删查效率 Log N ,迭代器遍历是走的搜索树的中序,所以是有序

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

  • 构造函数

a88ef7db19784861b49ecfdc53da6e2e.png

我们**一般需要提供

  1. T

键值**,

  1. Compare

仿函数默认是按升序排,有需求可以自行传入!!!

  1. Alloc

  1. set

中元素空间的管理方式,使用STL提供的空间配置器管理。所以一般我们不需要传递后两个参数。

  1. // empty (1) ⽆参默认构造
  2. explicit set (const key_compare& comp = key_compare(),
  3. const allocator_type& alloc = allocator_type());
  4. // range (2) 迭代器区间构造
  5. template <class InputIterator>
  6. set (InputIterator first, InputIterator last,
  7. const key_compare& comp = key_compare(),
  8. const allocator_type& = allocator_type());
  9. // copy (3) 拷⻉构造
  10. set (const set& x);
  11. // initializer list (5) initializer 列表构造
  12. set (initializer_list<value_type> il,
  13. const key_compare& comp = key_compare(),
  14. const allocator_type& alloc = allocator_type());
  15. // 迭代器是⼀个双向迭代器
  16. iterator -> a bidirectional iterator to const value_type
  17. // 正向迭代器
  18. iterator begin();
  19. iterator end();
  20. // 反向迭代器
  21. reverse_iterator rbegin();
  22. reverse_iterator rend();

与之前的容器大差不差,不再细说。

  • 增删查

set是不允许修改的,修改会破坏其BST的结构特征。

核心接口:

  1. Member types
  2. key_type->The first template parameter(T)
  3. value_type->The first template parameter(T)
  4. pair<iterator, bool> insert(const value_type& val);
  5. // 列表插⼊,已经在容器中存在的值不会插⼊
  6. void insert(initializer_list<value_type> il);
  7. // 迭代器区间插⼊,已经在容器中存在的值不会插⼊
  8. template <class InputIterator>
  9. void insert(InputIterator first, InputIterator last);
  10. // 查找val,返回val所在的迭代器,没有找到返回end()
  11. iterator find(const value_type& val);
  12. // 查找val,返回Val的个数
  13. size_type count(const value_type& val) const;
  14. // 删除⼀个迭代器位置的值
  15. iterator erase(const_iterator position);
  16. // 删除val,val不存在返回0,存在返回1
  17. size_type erase(const value_type& val);
  18. // 删除⼀段迭代器区间的值
  19. iterator erase(const_iterator first, const_iterator last);
  20. // 返回⼤于等val位置的迭代器
  21. iterator lower_bound(const value_type& val) const;
  22. // 返回⼤于val位置的迭代器
  23. iterator upper_bound(const value_type& val) const;

这里 key/value都是 T,set 本身并不需要value 这样设计为了和 map 保持一致性

f5cc53b83b2f4a8482efd488575981e7.png

**insert **

31181406fb64465fb634129fdc218f8d.png

  1. int main()
  2. {
  3. // 去重+升序排序
  4. set<int> s; // less 小的为真 到搜素树根左边去 greater时候 大的为真 到左边去
  5. // 去重+降序排序(给⼀个⼤于的仿函数)
  6. //set<int, greater<int>> s;
  7. s.insert(5);
  8. s.insert(2);
  9. s.insert(7);
  10. s.insert(5);
  11. // 插⼊⼀段initializer_list列表值,已经存在的值插⼊失败 //底层相当于一个一个调用 insert
  12. set<int>::iterator it = s.begin();
  13. while (it != s.end())
  14. {
  15. // error C3892: “it”: 不能给常量赋值
  16. // *it = 1;
  17. cout << *it << ' ';
  18. it++;
  19. }
  20. cout << endl;
  21. s.insert({ 2,8,3,9 });
  22. for (auto e : s)
  23. {
  24. cout << e << " ";
  25. }
  26. cout << endl;
  27. //void insert(initializer_list<value_type> il); 隐式类型转换了
  28. set<string>ss = { "sort", "insert", "add" };
  29. //set<string>ss = ( "sort", "insert", "add" ); 显示传 il
  30. // 遍历string⽐较ascll码⼤⼩顺序遍历的
  31. for (auto e : ss)
  32. {
  33. cout << e << ' ';
  34. }
  35. cout << endl;
  36. return 0;
  37. }

find 与 erase

c878746533df4ba9b15ad8a8def1aa03.png

  1. int main()
  2. {
  3. set<int> s = { 4,2,7,2,8,5,9 };
  4. for (auto e : s)
  5. {
  6. cout << e << " ";
  7. }
  8. cout << endl;
  9. // 删除最⼩值 默认情况升序
  10. s.erase(s.begin());
  11. for (auto e : s)
  12. {
  13. cout << e << " ";
  14. }
  15. cout << endl;
  16. // 直接删除x
  17. int x;
  18. cin >> x;
  19. int num = s.erase(x);
  20. if (num == 0)
  21. {
  22. cout << x << "不存在!" << endl;
  23. }
  24. for (auto e : s)
  25. {
  26. cout << e << " ";
  27. }
  28. cout << endl;
  29. // 直接查找在利⽤迭代器删除x 迭代器失效 1.删除叶子节点 野指针 2.删除根 换根失去原有意义 vs访问直接保持
  30. cin >> x;
  31. auto pos = s.find(x);
  32. if (pos != s.end())
  33. {
  34. s.erase(pos);
  35. }
  36. else
  37. {
  38. cout << x << "不存在!" << endl;
  39. }
  40. for (auto e : s)
  41. {
  42. cout << e << " ";
  43. }
  44. cout << endl;
  45. // 算法库的查找 O(N)
  46. auto pos1 = find(s.begin(), s.end(), x);
  47. // set⾃⾝实现的查找 O(logN)
  48. auto pos2 = s.find(x);
  49. // 利⽤count间接实现快速查找
  50. cin >> x;
  51. if (s.count(x)) // count 返回元素个数
  52. {
  53. cout << x << "在!" << endl;
  54. }
  55. else
  56. {
  57. cout << x << "不在!" << endl;
  58. }
  59. return 0;
  60. }

** 关于区间的删除**

  1. int main()
  2. {
  3. std::set<int> myset;
  4. for (int i = 1; i < 10; i++)
  5. myset.insert(i * 10); // 10 20 30 40 50 60 70 80 90
  6. for (auto e : myset)
  7. {
  8. cout << e << " ";
  9. }
  10. cout << endl;
  11. // 1.删除 [30,50]值
  12. // 2.删除 [25,55]值
  13. 实现查找到的[itlow,itup)包含[30, 50]区间
  14. 返回 >= 30
  15. //auto itlow = myset.lower_bound(30);
  16. 返回 > 50
  17. //auto itup = myset.upper_bound(50);
  18. //返回 >=25
  19. auto itlow = myset.lower_bound(25); //左闭
  20. //返回 >55
  21. auto itup = myset.upper_bound(55); //右开
  22. myset.erase(itlow, itup);
  23. for (auto e : myset)
  24. {
  25. cout << e << " ";
  26. }
  27. cout << endl;
  28. return 0;
  29. }

** multiset 与 set 接口差异**

  1. #include<iostream>
  2. #include<set>
  3. using namespace std;
  4. int main()
  5. {
  6. // 相⽐set不同的是,multiset是排序,但是不去重
  7. multiset<int> s = { 4,2,7,2,4,8,4,5,4,9 };
  8. auto it = s.begin();
  9. while (it != s.end())
  10. {
  11. cout << *it << " ";
  12. ++it;
  13. }
  14. cout << endl;
  15. // 相⽐set不同的是,x可能会存在多个,find查找中序的第⼀个 如何确定为中序第一个? 其左子树没有查找值即可
  16. int x;
  17. cin >> x;
  18. auto pos = s.find(x);
  19. while (pos != s.end() && *pos == x)
  20. {
  21. cout << *pos << " ";
  22. ++pos;
  23. }
  24. cout << endl;
  25. //pos = s.find(x);
  26. //while (pos != s.end() && *pos == x)
  27. //{
  28. // pos = s.erase(pos); //erase 传迭代器会返回下一个位置迭代器
  29. //}
  30. //cout << endl;
  31. // 相⽐set不同的是,count会返回x的实际个数
  32. cout << s.count(x) << endl;
  33. // 相⽐set不同的是,erase给值时会删除所有的x
  34. s.erase(x);
  35. for (auto e : s)
  36. {
  37. cout << e << " ";
  38. }
  39. cout << endl;
  40. return 0;
  41. }

3、map 与 multimap

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

map - C++ Reference

b6f1526faea145958747e8acbe25e4fd.png

  1. map是关联容器,它按照特定的次序(按照key来比较)存储由键值key和值value组合而成的元素。
  2. map中,键值key通常用于排序和惟一地标识元素,而值value中存储与此键值key关联的内容。键值key和值value的类型可能不同,并且在map的内部,keyvalue通过成员类型value_type绑定在一起,为其取别名称为pair:typedef pair<const key, T> value_type;
  3. 在内部,map中的元素总是按照键值key进行比较排序的。
  4. map中通过键值访问单个元素的速度通常比unordered_map容器慢,但map允许根据顺序对元素进行直接迭代(即对map中的元素进行迭代时,可以得到一个有序的序列)。
  5. map支持下标访问符,即在[ ]中放入key,就可以找到与key对应的value
  6. map通常被实现为二叉搜索树(更准确的说:平衡二叉搜索树(红黑树))。

map的声明如下,Key就是map底层关键字的类型,T是map底层value的类型

  1. template < class Key, // map::key_type
  2. class T, // map::mapped_type
  3. class Compare = less<Key>, // map::key_compare
  4. class Alloc = allocator<pair<const Key,T> > //
  5. map::allocator_type
  6. > class map;

•map默认要求Key支持小于比较,如果不支持或者想自己的需求来可以自行实现仿函数传给第三个模版参数
• map底层存储数据的内存是从空间配置器申请的,如果需要可以自己实现内存池,传给第个参
数。
• ⼀般情况下,我们都不需要传后两个模版参数。
• map底层是用红黑树实现,增删查效率 Log N ,迭代器遍历是走的搜索树的中序,所以是按照key有序遍历

pair 类型介绍
map底层的红黑树节点中的数据,使用 pair<Key,T> 存储键值对数据。

  1. // map 底层 value_type 原型解释
  2. typedef pair<const Key, T> value_type;
  3. // pair 原型
  4. template <class T1, class T2>
  5. struct pair
  6. {
  7. typedef T1 first_type;
  8. typedef T2 second_type;
  9. T1 first;
  10. T2 second;
  11. pair() : first(T1()), second(T2())
  12. {}
  13. pair(const T1& a, const T2& b) : first(a), second(b)
  14. {}
  15. template<class U, class V>
  16. pair(const pair<U, V>& pr) : first(pr.first), second(pr.second)
  17. {}
  18. };
  19. template <class T1, class T2>
  20. inline pair<T1, T2> make_pair(T1 x, T2 y)
  21. {
  22. return (pair<T1, T2>(x, y));
  23. }

f6cb292035764e2585b116a90001f4c7.png3.2 接口解析:常用操作与实现细节

  • 构造函数

2078b377dbf1428082a54a308304a613.png

**

  1. key

:键值对中key的类型

  1. T

: 键值对中

  1. value

的类型**

  1. Compare

: 比较器的类型,**

  1. map

中的元素是按照

  1. key

来比较的缺省情况下按照小于来比较,一般情况下(内置类型元素)该参数不需要传递,如果无法比较时(自定义类型),需要用户自己显式传递比较规则(一般情况下按照函数指针或者仿函数来传递)**

  1. Alloc

:通过空间配置器来申请底层空间,不需要用户传递,除非用户不想使用标准库提供的空间配置器

  1. // empty (1) ⽆参默认构造
  2. explicit map(const key_compare& comp = key_compare(),
  3. const allocator_type& alloc = allocator_type());
  4. // range (2) 迭代器区间构造
  5. template <class InputIterator>
  6. map(InputIterator first, InputIterator last,
  7. const key_compare& comp = key_compare(),
  8. const allocator_type & = allocator_type());
  9. // copy (3) 拷⻉构造
  10. map(const map& x);
  11. // initializer list (5) initializer 列表构造
  12. map(initializer_list<value_type> il,
  13. const key_compare& comp = key_compare(),
  14. const allocator_type& alloc = allocator_type());
  15. // 迭代器是⼀个双向迭代器
  16. iterator->a bidirectional iterator to const value_type
  17. // 正向迭代器
  18. iterator begin();
  19. iterator end();
  20. // 反向迭代器
  21. reverse_iterator rbegin();
  22. reverse_iterator rend();
  • 增删查

核心接口:

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

  1. Member types
  2. key_type->The first template parameter(Key)
  3. mapped_type->The second template parameter(T)
  4. value_type->pair<const key_type, mapped_type>
  5. // 单个数据插⼊,如果已经key存在则插⼊失败,key存在相等value不相等也会插⼊失败
  6. pair<iterator, bool> insert(const value_type& val);
  7. // 列表插⼊,已经在容器中存在的值不会插⼊
  8. void insert(initializer_list<value_type> il);
  9. // 迭代器区间插⼊,已经在容器中存在的值不会插⼊
  10. template <class InputIterator>
  11. void insert(InputIterator first, InputIterator last);
  12. // 查找k,返回k所在的迭代器,没有找到返回end()
  13. iterator find(const key_type& k);
  14. // 查找k,返回k的个数
  15. size_type count(const key_type& k) const;
  16. // 删除⼀个迭代器位置的值
  17. iterator erase(const_iterator position);
  18. // 删除k,k存在返回0,存在返回1
  19. size_type erase(const key_type& k);
  20. // 删除⼀段迭代器区间的值
  21. iterator erase(const_iterator first, const_iterator last);
  22. // 返回⼤于等于k位置的迭代器
  23. iterator lower_bound(const key_type& k);
  24. // 返回⼤于k位置的迭代器
  25. const_iterator lower_bound(const key_type& k) const;

map的删除查找与set 完全类似,不再赘述用例

  1. #include<iostream>
  2. #include<map>
  3. using namespace std;
  4. int main()
  5. {
  6. // initializer_list构造及迭代遍历
  7. map<string, string> dict = { {"left", "左边"}, {"right", "右边"},
  8. {"insert", "插入"},{ "string", "字符串" } };
  9. //map<string, string>::iterator it = dict.begin();
  10. auto it = dict.begin();
  11. while (it != dict.end())
  12. {
  13. //(*it).first += "xxx"; 不可以更改 key 可以更改value
  14. (*it).second += "xxx";
  15. //cout << (*it).first <<":"<<(*it).second << endl;
  16. // map的迭代基本都使⽤operator->,这⾥省略了⼀个->
  17. // 第⼀个->是迭代器运算符重载,返回pair*,第⼆个箭头是结构指针解引⽤取pair数据
  18. //cout << it.operator->()->first << ":" << it.operator->()-> second << endl;
  19. cout << it->first << ":" << it->second << endl;
  20. ++it;
  21. }
  22. cout << endl;
  23. // insert插⼊pair对象的4种⽅式,对⽐之下,最后⼀种最⽅便
  24. pair<string, string> kv1("first", "第一个");
  25. dict.insert(kv1);
  26. dict.insert(pair<string, string>("second", "第二个"));
  27. dict.insert(make_pair("sort", "排序"));
  28. dict.insert({ "auto", "自动的" });
  29. // "left"已经存在,插⼊失败
  30. dict.insert({ "left", "左边,剩余" });
  31. // 范围for遍历
  32. for (const auto& e : dict)
  33. {
  34. cout << e.first << ":" << e.second << endl;
  35. }
  36. cout << endl;
  37. string str;
  38. while (cin >> str)
  39. {
  40. auto ret = dict.find(str);
  41. if (ret != dict.end())
  42. {
  43. cout << "->" << ret->second << endl;
  44. }
  45. else
  46. {
  47. cout << "无此单词,请重新输入" << endl;
  48. }
  49. }
  50. return 0;
  51. }
  • map数据的修改 [ ]

map支持修改mapped_type 数据,不支持修改key数据,因为修改关键字数据,破坏了底层搜索树的结构。
map第一个支持修改的方式是通过迭代器,迭代器遍历时或者 find 返回 key 所在的 iterator 修 map
还有一个非常重要的修改接口 operator[ ] ,但是operator[ ]不仅仅支持修改,还支持插入数据和查找数据,所以他是⼀个多功能复合接口,需要注意从内部实现的角度,map这里把我们传统说的value值,给的是T类型,typedef为mapped_type。而value_type是红黑树结点中存储的pair键值对值。日常使用我们还是习惯将这里的T映射值叫做value。

  1. Member types
  2. key_type->The first template parameter(Key)
  3. mapped_type->The second template parameter(T)
  4. value_type->pair<const key_type, mapped_type>
  5. // 查找k,返回k所在的迭代器,没有找到返回end(),如果找到了通过iterator可以修改key对应mapped_type值
  6. iterator find(const key_type& k);
  7. // ⽂档中对insert返回值的说明
  8. // The single element versions (1) return a pair, with its member pair::first
  9. //set to an iterator pointing to either the newly inserted element or to the
  10. //element with an equivalent key in the map.The pair::second element in the pair
  11. //is set to true if a new element was inserted or false if an equivalent key
  12. //already existed.
  13. // insert插⼊⼀个pair<key, T>对象
  14. // 1、如果key已经在map中,插⼊失败,则返回⼀个pair<iterator,bool>对象,返回pair对象
  15. //first是key所在结点的迭代器,second是false
  16. // 2、如果key不在在map中,插⼊成功,则返回⼀个pair<iterator,bool>对象,返回pair对象
  17. //first是新插⼊key所在结点的迭代器,second是true
  18. // 也就是说⽆论插⼊成功还是失败,返回pair<iterator,bool>对象的first都会指向key所在的迭
  19. //代器
  20. // 那么也就意味着insert插⼊失败时充当了查找的功能,正是因为这⼀点,insert可以⽤来实现
  21. //operator[]
  22. // 需要注意的是这⾥有两个pair,不要混淆了,⼀个是map底层红⿊树节点中存的pair<key, T>,另
  23. //⼀个是insert返回值pair<iterator, bool>
  24. pair<iterator, bool> insert(const value_type& val);
  25. mapped_type& operator[] (const key_type& k);
  26. // operator的内部实现
  27. mapped_type& operator[] (const key_type& k)
  28. {
  29. // 1、如果k不在map中,insert会插⼊k和mapped_type默认值,同时[]返回结点中存储
  30. //mapped_type值的引⽤,那么我们可以通过引⽤修改返映射值。所以[]具备了插⼊ + 修改功能
  31. // 2、如果k在map中,insert会插⼊失败,但是insert返回pair对象的first是指向key结点的
  32. //迭代器,返回值同时[]返回结点中存储mapped_type值的引⽤,所以[]具备了查找 + 修改的功能
  33. pair<iterator, bool> ret = insert({ k, mapped_type() });
  34. iterator it = ret.first;
  35. return it->second;
  36. }

[ ]用例:

  1. int main()
  2. {
  3. string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
  4. "苹果", "香蕉", "苹果", "香蕉" };
  5. map<string, int> countMap;
  6. for (const auto& str : arr)
  7. {
  8. // 利⽤find和iterator修改功能,统计⽔果出现的次数
  9. 先查找⽔果在不在map
  10. 1、不在,说明⽔果第⼀次出现,则插⼊{⽔果, 1}
  11. 2、在,则查找到的节点中⽔果对应的次数++
  12. //auto ret = countMap.find(str);
  13. //if (ret == countMap.end())
  14. //{
  15. // countMap.insert({ str, 1 });
  16. //}
  17. //else
  18. //{
  19. //ret->second++;
  20. //}
  21. //利用 []的插入+查找+修改
  22. //[]先查找⽔果在不在map中
  23. // 1、不在,说明⽔果第⼀次出现,则插⼊{⽔果, 0},同时返回次数的引⽤,
  24. //++⼀下就变成1次了
  25. // 2、在,则返回⽔果对应的次数++
  26. countMap[str]++;
  27. }
  28. for (const auto & e : countMap)
  29. {
  30. cout << e.first << ":" << e.second << endl;
  31. }
  32. cout << endl;
  33. map<string, string> dict;
  34. dict.insert(make_pair("sort", "排序"));
  35. // key不存在->插⼊ {"insert", string()}
  36. dict["insert"];
  37. // 插⼊+修改
  38. dict["left"] = "左边";
  39. // 修改
  40. dict["left"] = "左边、剩余";
  41. // key存在->查找
  42. cout << dict["left"] << endl;
  43. // key不存在->插入 所以查找得确定 key存在情况下 否则可能为插入
  44. cout << dict["right"] << endl;
  45. for (const auto& e : dict)
  46. {
  47. cout << e.first << ":" << e.second << endl;
  48. }
  49. cout << endl;
  50. return 0;
  51. }

multimap 与 map 接口差异

multimap和map的使用基本完全类似,主要区别点在于multimap 支持关键值key冗余那么
insert/find/count/erase 都围绕着支持关键值key冗余有所差异
,这里跟set和multiset 完全⼀样

比如 find 时,有多个key,返回中序第⼀个。其次就是multimap不再支持[ ],因为支持 key 冗余

[ ]就只能支持插⼊了,不能支持修改。

4、OJ应用

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

1e21491cc3014630b4523988d4bc60b2.png

  1. class Solution {
  2. public:
  3. vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
  4. set<int>s1(nums1.begin(),nums1.end());
  5. set<int>s2(nums2.begin(),nums2.end()); //set 有序去重
  6. vector<int>ret;
  7. auto it1=s1.begin(); auto it2=s2.begin();
  8. while(it1!=s1.end()&&it2!=s2.end())
  9. {
  10. if(*it1<*it2)
  11. it1++;
  12. else if(*it1>*it2)
  13. it2++;
  14. else
  15. {
  16. ret.push_back(*it1);
  17. it1++;it2++;
  18. }
  19. }
  20. return ret;
  21. }
  22. };

分析:

set 去重+有序 双指针找交集

12c1eb8f03e348c5a87fbd20aa34850e.png

思考: 找差集呢? 双指针该如何操作

ca9e0ec7333e4ab39346e397381ecea3.png

小的就是差集,因为有序另一序列不可能比这个还小了

LCR 022. 环形链表 II - 力扣(LeetCode)

9c18779847f648dd9e22f0c1cf1bcde7.png

我们可以用快慢双指针的方法解决这个问题,但是这里为了兼容set,尝试使用set解决,利用set 唯一性解决环形链表交点问题

  1. class Solution {
  2. public:
  3. ListNode* detectCycle(ListNode* head) {
  4. set<ListNode*>s;
  5. ListNode* cur = head;
  6. while (cur)
  7. {
  8. /*auto ret = s.insert(cur);
  9. if (ret.second == false)
  10. return cur;
  11. cur = cur->next;*/
  12. if (s.count(cur))
  13. return cur;
  14. s.insert(cur);
  15. cur = cur->next;
  16. }
  17. return nullptr;
  18. }
  19. };

64776843dc1847519943bdec7b41da10.png

138. 随机链表的复制 - 力扣(LeetCode)

bd48520b72fd44debf40fb7818129239.png

  1. /*
  2. // Definition for a Node.
  3. class Node {
  4. public:
  5. int val;
  6. Node* next;
  7. Node* random;
  8. Node(int _val) {
  9. val = _val;
  10. next = NULL;
  11. random = NULL;
  12. }
  13. };
  14. */
  15. class Solution {
  16. public:
  17. Node* copyRandomList(Node* head) {
  18. map<Node*,Node*>nodeMap;
  19. Node* copyhead = nullptr,*copytail = nullptr;
  20. Node* cur = head;
  21. // 先复制节点结构
  22. while(cur)
  23. {
  24. if(copytail==nullptr)
  25. {
  26. copyhead=copytail=new Node(cur->val);
  27. }
  28. else
  29. {
  30. copytail->next=new Node(cur->val);
  31. copytail=copytail->next;
  32. }
  33. // 建立映射关系
  34. nodeMap[cur]=copytail;
  35. cur=cur->next;
  36. }
  37. // 随机指针的复制
  38. cur=head;
  39. Node*copycur=copyhead;
  40. while(cur)
  41. {
  42. if(cur->random==nullptr)
  43. {
  44. copycur->random=nullptr;
  45. }
  46. else
  47. {
  48. copycur->random=nodeMap[cur->random];
  49. }
  50. cur=cur->next;
  51. copycur=copycur->next;
  52. }
  53. return copyhead;
  54. }
  55. };

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

map 直接是可以字典序排序的,同时映射关系可以反应数量

  1. class Solution {
  2. public:
  3. struct Compare
  4. {
  5. bool operator()(const pair<string, int>& x, const pair<string, int>& y) const
  6. {
  7. return x.second > y.second;
  8. }
  9. };
  10. vector<string> topKFrequent(vector<string>& words, int k) {
  11. map<string, int> countMap;
  12. for(auto& e : words)
  13. {
  14. countMap[e]++;
  15. }
  16. vector<pair<string, int>> v(countMap.begin(), countMap.end());
  17. // 仿函数控制降序 稳定排序 这里自定义仿函数因为 我们只需要比较 pair.second
  18. stable_sort(v.begin(), v.end(), Compare());
  19. //sort(v.begin(), v.end(), Compare());
  20. vector<string>ret;
  21. for(int i=0;i<k;i++)
  22. {
  23. ret.push_back(v[i].first);
  24. }
  25. return ret;
  26. }
  27. };

这里使用了 stable_sort 事实上也可以用 sort 但是我们需要控制比较逻辑 确保字典序 不被打扰

  1. class Solution {
  2. public:
  3. struct Compare {
  4. bool operator()(const pair<string, int>& x,
  5. const pair<string, int>& y) const {
  6. return x.second > y.second ||
  7. (x.second == y.second && x.first < y.first);
  8. }
  9. };
  10. vector<string> topKFrequent(vector<string>& words, int k) {
  11. map<string, int> countMap;
  12. for (auto& e : words) {
  13. countMap[e]++;
  14. }
  15. vector<pair<string, int>> v(countMap.begin(), countMap.end());
  16. // 仿函数控制降序,仿函数控制次数相等,字典序⼩的在前⾯
  17. sort(v.begin(), v.end(), Compare());
  18. // 取前k个
  19. vector<string>ret;
  20. for(int i=0;i<k;i++)
  21. {
  22. ret.push_back(v[i].first);
  23. }
  24. return ret;
  25. }
  26. };

优先级队列实现策略:

  1. class Solution {
  2. public:
  3. struct Compare {
  4. bool operator()(const pair<string, int>& x,
  5. const pair<string, int>& y) const {
  6. // 要注意优先级队列底层是反的,⼤堆要实现⼩于⽐较,所以这⾥次数相等,想要字典
  7. // 序⼩的在前⾯要⽐较字典序⼤的为真
  8. return x.second < y.second ||
  9. (x.second == y.second && x.first > y.first);
  10. }
  11. };
  12. vector<string> topKFrequent(vector<string>& words, int k) {
  13. map<string, int> countMap;
  14. for (auto& e : words) {
  15. countMap[e]++;
  16. }
  17. // 将map中的<单词,次数>
  18. // 放到priority_queue中,仿函数控制⼤堆,次数相同按照字典序规则排序
  19. priority_queue<pair<string, int>, vector<pair<string, int>>, Compare> p(
  20. countMap.begin(), countMap.end());
  21. vector<string> ret;
  22. for (int i = 0; i < k; ++i) {
  23. ret.push_back(p.top().first);
  24. p.pop();
  25. }
  26. return ret;
  27. }
  28. };

可以看到仿函数的功能很强大,不过运用也得熟悉容器的底层框架,排序的逻辑

Thanks 谢谢阅读!

标签: c++ 开发语言

本文转载自: https://blog.csdn.net/2402_82668782/article/details/143705902
版权归原作者 如意.759 所有, 如有侵权,请联系我们删除。

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

还没有评论