当前位置:网站首页>两个数组的交集
两个数组的交集
2022-08-10 23:53:00 【老鱼37】
![在这里插入图片描述](https://img-blog.csdnimg.cn/8f978cc351c64e748910179903f1ad30.png)
****思路:
****第一种:
开辟一个新的数组,拿一个数组里面的每一个元素跟另一个数组比较,如果在另一个数组里面能找到的话将把重复的放入新的数组里面。**
****第二种:既然我们学过了unordered_set 我们就应该运用他的性质 ------不会包含重复的元素。****
1.将数组一元素放入unordered_set容器
2.创建一个set<int>容器 再用for(auto &ch:num2)遍历数组而,如果unordered_set中能够找到nums2中相应的元素,就把它放入set中
然后再用新数组接收set中的元素,返回这个新数组就行了********
**
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int>m(nums1.begin(),nums1.end());
set<int>p;
for(auto &ch:nums2)
{
if(m.count(ch))
{
p.insert(ch);
}
}
vector<int>k(p.begin(),p.end());
return k;
}
};
第三种:使用迭代器双指针的方法:
两个数组分别用set接收,set已经对数组元素大小排好序了,创建一个新数组,然后对两个set容器中的元素进行比较即可,相同的入,不同的跳
**
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int>v1(nums1.begin(),nums1.end());
set<int>v2(nums2.begin(),nums2.end());
vector<int>ans;
auto it1=v1.begin();
auto it2=v2.begin();
while(it1!=v1.end()&&it2!=v2.end())
{
if(*it1<*it2)
{
it1++;
}
else if(*it1>*it2)
{
it2++;
}
else
{
ans.push_back(*it1);
it1++;
it2++;
}
}
return ans;
}
};
有人就疑惑为什么要用set接收呢?不能用vector接收吗?
解:因为nums2中可能会出现重复出现的元素,比如nums2中有两个2,那么它就会把两个2都放进vector中,用set的好处是放入的元素不会重复。
如有错误,多多指教!
边栏推荐
- 【C语言】数据储存详解
- Is there a way out in the testing industry if it is purely business testing?
- 如何利用原生JS实现回到顶部以及吸顶效果
- 16. File upload
- How to recover data from accidentally deleted U disk, how to recover deleted data from U disk
- SAS数据处理技术(一)
- [Excel知识技能] 将数值格式数字转换为文本格式
- [C language] Detailed explanation of data storage
- 【C语言篇】操作符之 位运算符详解(“ << ”,“ >> ”,“ & ”,“ | ”,“ ^ ”,“ ~ ”)
- Dump file generation, content, and analysis
猜你喜欢
[C language] binary search (half search)
Server Tips
Ali P7 bask in January payroll: hard to fill the, really sweet...
软件测试证书(1)—— 软件评测师
2. Dependency management and automatic configuration
App regression testing, what are the efficient testing methods?
15. 拦截器-HandlerInterceptor
Dump file generation, content, and analysis
Easy-to-use translation plug-in - one-click automatic translation plug-in software
Promise in detail
随机推荐
Design and Realization of Employment Management System in Colleges and Universities
2. Dependency management and automatic configuration
The Missing Semester of Your CS Education
翻译软件哪个准确度高【免费】
Cache knowledge summary
【C语言篇】表达式求值(隐式类型转换,算术转换)
Where can I download IEEE papers?
ROS Experiment Notes - Validation of UZH-FPV Dataset
力扣每日一题-第52天-387. 字符串中的第一个唯一字符
sqlmap结合dnslog快速注入
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 2 DGHJKL Problem Solution
11. 自定义转换器
13. 内容协商
深度学习 Transformer架构解析
[21-day learning challenge - kernel notes] (5) - devmem read and write register debugging
关于科研学习中的几个问题:如何看论文?如何评价工作?如何找idea?
[Excel知识技能] 将文本型数字转换为数值格式
Web-based meal ordering system in epidemic quarantine area
电脑桌面删除的文件回收站没有,电脑上桌面删除文件在回收站找不到怎么办
[21天学习挑战赛——内核笔记](五)——devmem读写寄存器调试