leetcode刷题/哈希表 349. 两个数组的交集
2021/7/16 23:14:03
本文主要是介绍leetcode刷题/哈希表 349. 两个数组的交集,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
349. 两个数组的交集
题意:
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2] 输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出:[9,4]
解题思路:
具体步骤:
- 先用unordered_set存第一个数组
- 再用set存第二个(可以让数字不重复)
- 找到数字然后压入数组即可
利用set容器实现没能重复的特点,可以减去删除重复元素的操作,用这个思路我做了两个程序.
代码:
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> set_res; unordered_set<int> hash(nums1.begin(),nums1.end()); for (const int c:nums2) { if (hash.find(c) != hash.end()) set_res.insert(c); } vector<int> res(set_res.begin(),set_res.end()); return res; } };
运行过程:
代码:
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> res; unordered_set<int> hash(nums1.begin(),nums1.end()); set<int> f(nums2.begin(), nums2.end()); for (const int c:f) { if (hash.find(c) != hash.end()) res.push_back(c); } return res; } };
运行结果:
总结:
两个代码思路是一样的,所以运行结果差不多.这道题要注意的是它没有说数据多大,所以不能用数组来存储,另外一个就是要利用set容器可以让重复的元素去除的特性.
这篇关于leetcode刷题/哈希表 349. 两个数组的交集的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-07Dify + TiDB Vector,快速构建你的AI Agent
- 2024-07-06有没有什么开源的py项目可以对图像进行分类-icode9专业技术文章分享
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享