当前位置:网站首页>349. 两个数组的交集
349. 两个数组的交集
2022-07-26 10:42:00 【Forest_1010】

首先使用两个集合分别存储两个数组中的元素,然后遍历其中的一个集合,判断其中的每个元素是否在另一个集合中,如果元素也在另一个集合中,则将该元素添加到返回值。该方法的时间复杂度可以降低到 O(m+n)
集合分为三种:
- std::set
底层实现:红黑树
是否有序:有序
数值是否可以重复:否
查询效率:O(logn) - std::multiset
底层实现:红黑树
是否有序:有序
数值是否可以重复:是
查询效率:O(logn) - std::unordered_set
底层实现:哈希表
是否有序:无序
数值是否可以重复:否
查询效率:O(1)
综上,使用unordered_set效率是最高的。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set;
unordered_set<int> nums1_set(nums1.begin(), nums1.end());//将num1中的数据存入到nums1_set
unordered_set<int> nums2_set(nums2.begin(), nums2.end());//nums1_set,nums2_set中都没有重复的元素了
for (int num : nums2_set) //遍历nums2_set:从数组nums2依次取出元素赋值给整型变量nums,循环执行for中语句
{
//如果 存在:查找num是否存在,存在返回该元素的迭代器,不存在返回nums1_set.end();
if (nums1_set.find(num) != nums1_set.end()) //在集合1中查找,发现也有集合2中的这个元素
{
result_set.insert(num);
}
}
return vector<int>(result_set.begin(), result_set.end());
}
};
边栏推荐
- Mlx90640 infrared thermal imager temperature sensor module development notes (VI) pseudo color coding of infrared images
- .net5wtm (asp.net core) PgSQL unpacking operation
- 在神州IV开发板上为STemWin 5.22加入触屏驱动
- Redis implementation of distributed lock solution
- 鹏哥C语言20210811程序结构作业
- 剑指Offer(四十三):左旋转字符串
- 剑指Offer(二十一):栈的压入、弹出序列
- RT-Thread 学习笔记(七)---开启基于SPI Flash的elmfat文件系统(中)
- 超图 影像 如何去除黑边(两种方法)
- 从蚂蚁的觅食过程看团队研发(转载)
猜你喜欢

Disable usbjatg in Altium Designer

kali 查看ip地址

RT-Thread 学习笔记(一)---配置RT-Thread开发环境

Add touch screen driver for stemwin 5.22 on Shenzhou IV development board

Analysis of the transaction problem of chained method call

【机器学习小记】【人脸识别】deeplearning.ai course4 4th week programming

Uniapp uses the simple method signalr (only for web debugging, cannot package apps)

Codepoint 58880 not found in font, aborting. flutter build apk时报错

putty的使用教程

RT thread learning notes (III) -- building a compilation environment with scons
随机推荐
剑指Offer(十):矩形覆盖
粽子大战 —— 猜猜谁能赢
Issue 6: which mainstream programming language should college students choose
.net operation redis sorted set ordered set
Successfully transplanted stemwin v5.22 on Shenzhou IV development board
.net operation redis string string
mysql20210906
使用flex实现左中右布局,中间自适应
Flutter报错 Incorrect use of ParentDataWidget When the exception was thrown, this was the stack:
toolstrip 去边框
A semicolon is missing
Zongzi battle - guess who can win
Sql Server之查询总结
第8期:云原生—— 大学生职场小白该如何学
$router和$route的区别
RT thread learning notes (I) -- configure RT thread development environment
putty的使用教程
一文详解Nodejs中fs文件模块与path路径模块
Dry goods likeshop takeout order system is open source, 100% open source, no encryption
flutter dart生成N个区间范围内不重复随机数List