博客
关于我
leetcode刷题42——数组的交集系列
阅读量:727 次
发布时间:2019-03-21

本文共 1790 字,大约阅读时间需要 5 分钟。

给定两个数组,编写一个函数来计算它们的交集。输出结果中的每个元素一定是唯一的,可以不考虑输出结果的顺序。

方法一:使用排序和集合

这种方法通过对两个数组进行排序,然后使用标准库中的set_intersection函数找出交集元素。最后,使用unique函数去除重复元素:

#include 
#include
#include
using namespace std;vector
intersection(vector
& nums1, vector
& nums2) { vector
v; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); set_intersection(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), back_inserter(v)); auto it = unique(v.begin(), v.end()); if (it != v.end()) { v.erase(it, v.end()); } return v;}

方法二:使用哈希表

这种方法通过先将数组元素映射到哈希表中,然后检查元素是否存在于两个哈希表中,从而记录交集元素:

#include 
#include
using namespace std;vector
intersection(vector
& nums1, vector
& nums2) { unordered_set
hash1; unordered_set
hash2; vector
v; for (int num : nums1) { hash1.insert(num); } for (int num : nums2) { if (hash1.count(num) && !hash2.count(num)) { v.push_back(num); } hash2.insert(num); } return v;}

方法三:处理频率最低的元素

这种方法通过统计每个元素的频率,取两个数组中最小频率的元素:

#include 
#include
using namespace std;vector
intersect(const vector
& nums1, const vector
& nums2) { unordered_map
counter; for (int num : nums1) { counter[num]++; } vector
result; for (int num : nums2) { if (counter[num] > 0) { result.push_back(num); counter[num]--; } } return result;}

选择方法

选择哪一种方法取决于具体需求。第一种方法简单且有效,但在处理大数据量时可能较慢。第二种方法通过哈希表提高了效率,第三种方法则处理了元素频率的问题。

按照题目要求,每个元素在结果中只出现一次,因此无论选择哪种方法,只要确保交集元素唯一即可。如果需要优化性能,第二种方法通常更好。

转载地址:http://wvfgz.baihongyu.com/

你可能感兴趣的文章
Python3.x:遍历select下拉框获取value值
查看>>
python360百科_11月编程排行榜:Python超过Java成第二
查看>>
Python关于Paginator分页函数详细解析 附实战代码
查看>>
python3、ipython3、setup-tools、pip等环境搭建详细总结
查看>>
python3下使用cv2.imwrite存储带有中文路径图片或者绝对路径图片
查看>>
python3与django中@property详解
查看>>
python3中如何表示无穷大
查看>>
Python3中提示:no module named 'wxpy'
查看>>
python3中选择文件对话框的格式打开和保存图片
查看>>
python3为什么print永远都是地址_Python3 print 函数用法总结
查看>>
Python3之uuid模块
查看>>
Python3之写入Excel文档(xlsxwriter)
查看>>
Python3之打印操作打印流重定向(下)
查看>>
python3判断字典、列表、元组为空以及字典是否存在某个key的方法
查看>>
Python3利用pymysql操作 MySQL
查看>>
python3处理json文件中含有中文dumps的应用
查看>>
Python3子进程输出
查看>>
Python3学习笔记3,变量、运算符
查看>>
Python3学习笔记(urllib模块的使用)
查看>>
python3安装scapy_Linux下安装scapy-python3
查看>>