当前位置:网站首页>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());
}
};
边栏推荐
- Build ARM embedded development environment
- 剑指Offer(二十):包含min函数的栈
- 剑指Offer(八):跳台阶
- 第5期:大学生入职必备技能之二
- flutter dart生成N个区间范围内不重复随机数List
- .net operation redis set unordered collection
- PLC与伺服电机连接
- Flutter报错 Incorrect use of ParentDataWidget When the exception was thrown, this was the stack:
- Koin
- Parallelism, concurrency and several directions for high concurrency optimization
猜你喜欢

RT thread learning notes (III) -- building a compilation environment with scons

【机器学习小记】【人脸识别】deeplearning.ai course4 4th week programming
![[paper after dinner] deep mining external perfect data for chestx ray disease screening](/img/d6/41c75d292c26b2e7e116767a51eb5e.png)
[paper after dinner] deep mining external perfect data for chestx ray disease screening

【机器学习小记】【风格迁移】deeplearning.ai course4 4th week programming(tensorflow2)

SAP ABAP 守护进程的实现方式

sigmod 函数与softmax 函数对比

Redis docker instance and data structure

Write to esp8266 burning brush firmware

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

Centos8 (liunx) deploying WTM (asp.net 5) using PgSQL
随机推荐
Redis implementation of distributed lock solution
Database functions
7-25 0-1背包 (50分)
第5期:大学生入职必备技能之二
A semicolon is missing
RT-Thread 学习笔记(六)--- 开启基于SPI Flash的elmfat文件系统(上)
The problem of large fluctuation of hx711 data
mysql20210906
Oracle cannot start tnslistener service cannot start
[leetcode daily question 2021/2/18] [detailed explanation] minimum number of turns of 995. K continuous bits
RT thread learning notes (VIII) -- start the elmfat file system based on SPI flash (Part 2)
对面向抽象编程的理解
(转载)ArcGIS Engine中各种点的创建方法
Flutter编译报错 version of NDK matched the requested version 21.0.6113669. Versions available locally: 2
IAR sprintf 浮点 在UCOS 总格式化成0.0的问题
[leetcode daily question 2021/4/23]368. Maximum divisible subset
MFC多线程的简单使用
Constructors, method overloads, object arrays, and static
The problem of formatting IAR sprintf floating point to 0.0 in UCOS assembly
27.移除元素