当前位置:网站首页>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());
}
};
边栏推荐
- RT thread learning notes (VII) -- open the elmfat file system based on SPI flash (middle)
- Halcon模板匹配之Shape
- [leetcode daily question 2021/8/31] 1109. Flight reservation statistics [medium] differential array
- Flutter 防止科学计数并去除尾数无效0
- algorithm
- 20210807#1 C语言程序结构
- SAP ABAP 守护进程的实现方式
- Flutter TextField设置高度并且自动换行,圆角边框去除下划线
- 在神州IV开发板上为STemWin 5.22加入触屏驱动
- Application of.Net open source framework in industrial production
猜你喜欢
Zongzi battle - guess who can win
Error[pe147]: declaration is incompatible with 'error problem
[machine learning notes] [style transfer] deeplearning ai course4 4th week programming(tensorflow2)
解决:无法加载文件 C:\Users\user\AppData\Roaming\npm\npx.ps1,因为在此系统上禁止运行脚本 。
[paper after dinner] deep mining external perfect data for chestx ray disease screening
【机器学习小记】【风格迁移】deeplearning.ai course4 4th week programming(tensorflow2)
【机器学习小记】【搭建循环神经网络及其应用】deeplearning.ai course5 1st week programming(keras)
flutter 背景变灰效果,如何透明度,灰色蒙板遮罩
RT-Thread 学习笔记(七)---开启基于SPI Flash的elmfat文件系统(中)
在altium designer中禁用USBJATG
随机推荐
鹏哥C语言第七节课总结
RT thread learning notes (VIII) -- start the elmfat file system based on SPI flash (Part 2)
Redis special data type usage scenarios
Koin
Sql Server 之SQL语句对基本表及其中的数据的创建和修改
Add touch screen driver for stemwin 5.22 on Shenzhou IV development board
[machine learning notes] [face recognition] deeplearning ai course4 4th week programming
多目标优化系列1---NSGA2的非支配排序函数的讲解
12 don't forget every component when copying an object
剑指Offer(四十九):把字符串转换成整数
[leetcode daily question 2021/2/13]448. Find all the missing numbers in the array
Dry goods likeshop takeout order system is open source, 100% open source, no encryption
Problems encountered in QRcode QR code (C language)
剑指Offer(四十三):左旋转字符串
Flutter TextField怎样去除下划线及有焦点时颜色
在神州IV开发板上为STemWin 5.22加入触屏驱动
.net operation redis list list
[leetcode daily question 2021/4/29]403. Frogs cross the river
剑指Offer(七):斐波那契数列
从蚂蚁的觅食过程看团队研发(转载)